Core Java
Core Java
com
tech facts at your fingertips
CONTENTS INCLUDE:
n
Java Keywords
n
Standard Java Packages
n
Character Escape Sequences
n
Collections and Common Algorithms
n
Regular Expressions
n
JAR Files
This refcard gives you an overview of key aspects of the Java
language and cheat sheets on the core library (formatted
output, collections, regular expressions, logging, properties)
as well as the most commonly used tools (javac, java, jar).
Java Keywords, continued
ABOUT CORE JAVA
JAVA KEYWORDS
C
o
r
e
J
a
v
a
w
w
w
.
d
z
o
n
e
.
c
o
m
S
u
b
s
c
r
i
b
e
N
o
w
f
o
r
F
R
E
E
!
r
e
f
c
a
r
d
z
.
c
o
m
n
Authoritative content
n
Designed for developers
n
Written by top experts
n
Latest tools & technologies
n
Hot tips & examples
n
Bonus content online
n
New issue every 1-2 weeks
Subscribe Now for FREE!
Refcardz.com
Get More Refcardz
(Theyre free!)
Core Java
By Cay S. Horstmann
Typical usage:
String msg = MessageFormat.format("On {1, date,
long}, a {0} caused {2,number,currency} of damage.",
"hurricane", new GregorianCalendar(2009, 0, 15).
getTime(), 1.0E8);
Yields "On January 1, 1999, a hurricane caused
$100,000,000 of damage"
n
The nth item is denoted by {n,format,subformat} with
optional formats and subformats shown below
n
{0} is the rst item
n
The following table shows the available formats
n
Use single quotes for quoting, for example '{' for a literal
left curly brace
n
Use '' for a literal single quote
FORMATTED OUTPUT WITH MessageFormat
Flag Description Example
+ Prints sign for positive and negative numbers +3333.33
space Adds a space before positive numbers | 3333.33|
0 Adds leading zeroes 003333.33
- Left-justies eld |3333.33 |
( Encloses negative number in parentheses (3333.33)
, Adds group separators 3,333.33
# (for f format) Always includes a decimal point 3,333.
# (for x or o
format)
Adds 0x or 0 prex 0xcafe
$ Species the index of the argument to be formatted;
for example, %1$d %1$x prints the rst argument in
decimal and hexadecimal
159 9F
< Formats the same value as the previous specication;
for example, %d %<x prints the same number in decimal
and hexadecimal
159 9F
Conversion
Character
Description Example
d Decimal integer 159
x Hexadecimal integer 9f
o Octal integer 237
f Fixed-point oating-point 15.9
e Exponential oating-point 1.59e+01
g General oating-point (the shorter of e and f)
a Hexadecimal oating-point 0x1.fccdp3
s String Hello
c Character H
b boolean true
h Hash code 42628b2
tx Date and time See the next table
% The percent symbol %
n The platform-dependent line separator
Typical usage
System.out.printf("%4d %8.2f", quantity, price);
String str = String.format("%4d %8.2f", quantity, price);
Each format specier has the following form. See the tables for
ags and conversion characters.
Flags
Conversion characters
FORMATTED OUTPUT WITH printf
CHARACTER ESCAPE SEQUENCES
\b backspace \u0008
\t tab \u0009
\n newline \u000A
\f form feed \u000C
\r carriage return \u000D
\" double quote
\' single quote
\\ backslash
\uhhhh (hhhh is a hex number between 0000 and FFFF) The UTF-16 code point with value hhhh
\ooo (ooo is an octal number between 0 and 377) The character with octal value ooo
Note: Unlike in C/C++, \xhh is not allowed
Common Tasks
COLLECTIONS AND COMMON ALGORITHMS
ArrayList An indexed sequence that grows and shrinks dynamically
LinkedList An ordered sequence that allows efcient insertions and removal at
any location
ArrayDeque A double-ended queue that is implemented as a circular array
HashSet An unordered collection that rejects duplicates
TreeSet A sorted set
EnumSet A set of enumerated type values
LinkedHashSet A set that remembers the order in which elements were inserted
PriorityQueue A collection that allows efcient removal of the smallest element
HashMap A data structure that stores key/value associations
TreeMap A map in which the keys are sorted
EnumMap A map in which the keys belong to an enumerated type
LinkedHashMap A map that remembers the order in which entries were added
WeakHashMap A map with values that can be reclaimed by the garbage collector if
they are not used elsewhere
IdentityHashMap A map with keys that are compared by ==, not equals
List<String> strs = new ArrayList<String>(); Collect strings
strs.add("Hello"); strs.add("World!"); Add strings
for (String str : strs) System.out.println(str); Do something with all elements
in the collection
Iterator<String> iter = strs.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition(str)) iter.remove();
}
Remove elements that match a
condition. The remove method
removes the element returned by
the preceding call to next.
strs.addAll(strColl); Add all strings from another
collection of strings
strs.addAll(Arrays.asList(args)) Add all strings from an array of
strings. Arrays.asList makes a
List wrapper for an array
strs.removeAll(coll); Remove all elements of another
collection. Uses equals for
comparison
if (0 <= i && i < strs.size()) {
str = strs.get(i);
strs.set(i, "Hello");
}
Get or set an element at a
specied index
strs.insert(i, "Hello");
str = strs.remove(i);
Insert or remove an element at
a specied index, shifting the
elements with higher index values
String[] arr = new String[strs.size()];
strs.toArray(arr);
Convert from collection to array
String[] arr = ...;
List<String> lst = Arrays.asList(arr);
lst = Arrays.asList("foo", "bar", "baz");
Convert from array to list. Use
the varargs form to make a small
collection.
List<String> lst = ...;
lst.sort();
lst.sort(new Comparator<String>() {
public int compare(String a, String b) {
return a.length() - b.length();
}
}
Sort a list by the natural order of
the elements, or with a custom
comparator.
Map<String, Person> map = new
LinkedHashMap<String, Person>();
Make a map that is traversed in
insertion order (requires hashCode
for key type). Use a TreeMap to
traverse in sort order (requires that
key type is comparable).
for (Map.Entry<String, Person> entry :
map.entrySet()) {
String key = entry.getKey();
Person value = entry.getValue();
...
}
Iterate through all entries of the
map
Person key = map.get(str); // null if not found
map.put(key, value);
Get or set a value for a given key
4
DZone, Inc. | www.dzone.com
Core Java
tech facts at your fingertips
Predened Character Class Names
Flags for matching
The pattern matching can be adjusted with ags, for example:
Pattern pattern = Pattern.compile(patternString,
Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE)
Characters
c The character c
\unnnn, \xnn,
\0n, \0nn,
\0nnn
The code unit with the given hex or octal value
\t, \n, \r,
\f, \a, \e
The control characters tab, newline, return, form feed, alert, and escape
\cc The control character corresponding to the character c
Character Classes
[C
1
C
2
. . .] Union: Any of the characters represented by C
1
C
2
, . . .
The C
i
are characters, character ranges c
1
-c
2
, or character classes.
Example: [a-zA-Z0-9_]
[^C
1
C
2
. . .] Complement: Characters not represented by any of C
1
C
2
, . . .
Example: [^0-9]
[C
1
&&C
2
&&. . .] Intersection: Characters represented by all of C
1
C
2
, . . .
Example: [A-f&&[^G-`]]
Predened Character Classes
. Any character except line terminators (or any character if the DOTALL
ag is set)
\d A digit [0-9]
\D A nondigit [^0-9]
\s A whitespace character [ \t\n\r\f\x0B]
\S A nonwhitespace character
\w A word character [a-zA-Z0-9_]
\W A nonword character
\p{name} A named character classsee table below
\P{name} The complement of a named character class
Boundary Matchers
^ $ Beginning, end of input (or beginning, end of line in multiline mode)
\b A word boundary
\B A nonword boundary
\A Beginning of input
\z End of input
\Z End of input except nal line terminator
\G End of previous match
Quantiers
X? Optional X
X* X, 0 or more times
X+ X, 1 or more times
X{n} X{n,} X{n,m} X n times, at least n times, between n and m times
Quantier Sufxes
? Turn default (greedy) match into reluctant match
+ Turn default (greedy) match into reluctant match
Set Operations
XY Any string from X, followed by any string from Y
X |Y Any string from X or Y
Grouping
(X) Capture the string matching X as a group
\g The match of the gth group
Escapes
\c The character c (must not be an alphabetic character)
\Q . . . \E Quote . . . verbatim
(? . . . ) Special constructsee API notes of Pattern class
Lower ASCII lower case [a-z]
Upper ASCII upper case [A-Z]
Alpha ASCII alphabetic [A-Za-z]
Digit ASCII digits [0-9]
Alnum ASCII alphabetic or digit [A-Za-z0-9]
XDigit Hex digits [0-9A-Fa-f]
Print or Graph Printable ASCII character [\x21-\x7E]
Punct ASCII nonalpha or digit [\p{Print}&&\P{Alnum}]
ASCII All ASCII [\x00-\x7F]
Cntrl ASCII Control character [\x00-\x1F]
Blank Space or tab [ \t]
Space Whitespace [ \t\n\r\f\0x0B]
javaLowerCase Lower case, as determined by Character.isLowerCase()
javaUpperCase Upper case, as determined by Character.isUpperCase()
javaWhitespace White space, as determined by Character.isWhiteSpace()
javaMirrored Mirrored, as determined by Character.isMirrored()
InBlock Block is the name of a Unicode character block, with spaces
removed, such as BasicLatin or Mongolian.
Category or InCategory Category is the name of a Unicode character category such
as L (letter) or Sc (currency symbol).
Flag Description
CASE_INSENSITIVE Match characters independently of the letter case. By default,
this ag takes only US ASCII characters into account.
UNICODE_CASE When used in combination with CASE_INSENSITIVE, use Unicode
letter case for matching.
MULTILINE ^ and $ match the beginning and end of a line, not the entire input.
UNIX_LINES Only '\n' is recognized as a line terminator when matching ^
and $ in multiline mode.
DOTALL When using this ag, the . symbol matches all characters,
including line terminators.
CANON_EQ Takes canonical equivalence of Unicode characters into account.
For example, u followed by (diaeresis) matches .
LITERAL The input string that species the pattern is treated as a sequence
of literal characters, without special meanings for . [ ] etc.
Common Tasks
Regular Expression Syntax
Regular Expression Syntax, continued Formatted Output with MessageFormat, continued
REGULAR EXPRESSIONS
Format Subformat Example
number none 1,234.567
integer 1,235
currency $1,234.57
percent 123,457%
date none or medium Jan 15, 2009
short 1/15/09
long January 15, 2009
full Thursday, January 15, 2009
time none or medium 3:45:00 PM
short 3:45 PM
long 3:45:00 PM PST
full 3:45:00 PM PST
choice List of choices, separated by |. Each choice has
n a lower bound (use -\u221E for -)
na relational operator: < for less than, # or
\u2264 for
n a message format string
For example, {1,choice,0#no houses|1#one
house|2#{1} houses}
no house
one house
5 houses
String[] words = str.split("\\s+"); Split a string along white
space boundaries
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(str);
String result = matcher.replaceAll("#");
Replace all matches.
Here we replace all digit
sequences with a #.
Pattern pattern = Pattern.compile("[0-9]+");
Matcher matcher = pattern.matcher(str);
while (matcher.fnd()) {
process(str.substring(matcher.start(), matcher.end()));
}
Find all matches.
Pattern pattern = Pattern.compile(
"(1?[0-9]):([0-5][0-9])[ap]m");
Matcher matcher = pattern.matcher(str);
for (int i = 1; i <= matcher.groupCount(); i++) {
process(matcher.group(i));
}
Find all groups (indicated
by parentheses in the
pattern). Here we nd
the hours and minutes
in a date.
5
DZone, Inc. | www.dzone.com
Core Java
tech facts at your fingertips
n
Contain name/value pairs, separated by =, :, or whitespace
n
Whitespace around the name or before the start of the
value is ignored
n
Lines can be continued by placing an \ as the last character;
leading whitespace on the continuation line is ignored
button1.tooltip = This is a long \
tooltip text.
n
\t \n \f \r \\ \uxxxx escapes are recognized (but not \b
or octal escapes)
n
Files are assumed to be encoded in ISO 8859-1; use
native2ascii to encode non-ASCII characters into
Unicode escapes
n
Blank lines and lines starting with # or ! are ignored
Typical usage:
Properties props = new Properties();
props.load(new FileInputStream("prog.properties"));
String value = props.getProperty("button1.tooltip");
// null if not present
Also used for resource bundles:
ResourceBundle bundle = ResourceBundle.getBundle("prog");
// Searches for prog_en_US.properties,
// prog_en.properties, etc.
String value = bundle.getString("button1.tooltip");
n
Used for storing applications, code libraries
n
By default, class les and other resources are stored in
ZIP le format
n
META-INF/MANIFEST.MF contains JAR metadata
n
META-INF/services can contain service provider
conguration
n
Use the jar utility to make JAR les
jar Utility Options
PROPERTY FILES
JAR FILES
Option Description
c Creates a new or empty archive and adds les to it. If any of the specied le
names are directories, the jar program processes them recursively.
C Temporarily changes the directory. For example,
jar cvfC myprog.jar classes *.class
changes to the classes subdirectory to add class les.
e Creates a Main-Class entry in the manifest
jar cvfe myprog.jar com.mycom.mypkg.MainClass fles
f Species the JAR le name as the second command-line argument. If this
parameter is missing, jar will write the result to standard output (when creating a
JAR le) or read it from standard input (when extracting or tabulating a JAR le).
i Creates an index le (for speeding up lookups in a large archive)
m Adds a manifest to the JAR le.
jar cvfm myprog.jar mymanifest.mf fles
M Does not create a manifest le for the entries.
t Displays the table of contents.
jar tvf myprog.jar
u Updates an existing JAR le
jar uf myprog.jar com/mycom/mypkg/SomeClass.class
v Generates verbose output.
x Extracts les. If you supply one or more le names, only those les are
extracted. Otherwise, all les are extracted.
jar xf myprog.jar
O Stores without ZIP compression
Common Tasks
Logging Conguration Files
The logging conguration can be congured through a logging
conguration le, by default jre/lib/logging.properties.
Another le can be specied with the system property java.
util.logging.confg.fle when starting the virtual machine.
(Note that the LogManager runs before main.)
LOGGING
Logger logger =
Logger.getLogger("com.mycompany.myprog.mycategory");
Get a logger for a category
logger.info("Connection successful."); Logs a message of level FINE.
Available levels are SEVERE,
WARNING,INFO,CONFIG,FINE,
FINER, FINEST, with
corresponding methods severe,
warning, and so on.
logger.log(Level.SEVERE, "Unexpected exception",
throwable);
Logs the stack trace of a
Throwable
logger.setLevel(Level.FINE); Sets the logging level to FINE.
By default, the logging level is
INFO, and less severe logging
messages are not logged.
Handler handler = new FileHandler("%h/myapp.log",
SIZE_LIMIT, LOG_ROTATION_COUNT);
handler.setFormatter(new SimpleFormatter());
logger.addHandler(handler);
Adds a le handler for saving the
log records in a le. See the table
below for the naming pattern. This
handler uses a simple formatter
instead of the XML formatter that
is the default for le handlers.
Conguration Property Description Default
loggerName.level The logging level of the logger by the
given name
None; the logger
inherits the handler
from its parent
handlers A whitespace or comma-separated list
of class names for the root logger. An
instance is created for each class name,
using the default constructor.
java.util.logging.
ConsoleHandler
loggerName.handlers A whitespace or comma-separated list
of class names for the given logger
None
loggerName.
useParenthandlers
false if the parent logger's handlers
(and ultimately the root logger's
handlers) should not be used
true
confg A whitespace or comma-separated list
of class names for initialization.
None
java.util.logging.
FileHandler.level
java.util.logging.
ConsoleHandler.level
The default handler level Level.ALL for
FileHandler,
Level.INFO for
ConsoleHandler
java.util.logging.
FileHandler.formatter
java.util.logging.
ConsoleHandler.formatter
The class name of the default lter None
java.util.logging.
FileHandler.formatter
java.util.logging.
ConsoleHandler.formatter
The class name of the default formatter java.util.logging.
XMLFormatter for
FileHandler,
java.util.logging.
SimpleFormatter for
ConsoleHandler
java.util.logging.
FileHandler.encoding
java.util.logging.
ConsoleHandler.encoding
The default encoding default platform
encoding
java.util.logging.
FileHandler.limit
The default limit for rotating log les,
in bytes
0 (No limit), but set
to 50000 in jre/lib/
logging.properties
java.util.logging.
FileHandler.count
The default number of rotated log les 1
java.util.logging.
FileHandler.pattern
The default naming pattern for log les.
The following tokens are replaced when
the le is created:
%h/java%u.log
java.util.logging.
FileHandler.append
The default append mode for le loggers;
true to append to an existing log le
false
Token Description
/ Path separator
%t System temporary directory
%h Value of user.home system property
%g The generation number of rotated logs
%u A unique number for resolving
naming conicts
%% The % character
Core Java
6
tech facts at your fingertips
DZone communities deliver over 3.5 million pages per month to
more than 1.5 million software developers, architects and designers.
DZone offers something for every developer, including news,
tutorials, blogs, cheatsheets, feature articles, source code and more.
DZone is a developers dream, says PC Magazine.
DZone, Inc.
1251 NW Maynard
Cary, NC 27513
888.678.0399
919.678.0300
Refcardz Feedback Welcome
refcardz@dzone.com
Sponsorship Opportunities
sales@dzone.com
Copyright 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying,
or otherwise, without prior written permission of the publisher. Reference: Core Java, Volume I and Core Java, Volume II, Cay S. Horstmann and Gary Cornell, Sun Microsystems Press, 1996-2007.
Version 1.0
$
7
.
9
5
ISBN-13: 978-1-934238-26-4
ISBN-10: 1-934238-26-0
9 781934 238264
5 0 7 9 5
ABOUT THE AUTHOR
Core Java, now in
its 8th edition, is a
no-nonsense tutorial
and reliable reference
into all aspects of
Java SE 6.
RECOMMENDED BOOKS
BUY NOW
books.dzone.com/books/corejava1
books.dzone.com/books/corejava2
Cay S. Horstmann
Cay S. Horstmann has written many books on C++, Java and object-
oriented development, is the series editor for Core Books at Prentice-Hall
and a frequent speaker at computer industry conferences. For four years,
Cay was VP and CTO of an Internet startup that went from 3 people in a
tiny ofce to a public company. He is now a computer science professor
at San Jose State University. He was elected Java Champion in 2005.
Publications
n
Core Java, with Gary Cornell (Sun Microsystems Press 19962007)
n
Core JavaServer Faces, with David Geary (Sun Microsystems Press 20042006)
n
Big Java (John Wiley & Sons 20012007)
Web Site Blog
http://horstmann.com http://weblogs.java.net/blog/cayhorstmann
COMMON javac OPTIONS COMMON java OPTIONS
Option Purpose
-cp or -classpath Sets the class path, used to search for class les. The class path is a
list of directories, JAR les, or expressions of the form directory/'*'
(Unix) or directory\* (Windows). The latter refers to all JAR les
in the given directory. Class path items are separated by : (Unix)
or ; (Windows). If no class path is specied, it is set to the current
directory. If a class path is specied, the current directory is not
automatically includedadd a . item if you want to include it.
-sourcepath Sets the path used to search for source les. If source and class les
are present for a given le, the source is compiled if it is newer. If no
source path is specied, it is set to the current directory.
-d Sets the path used to place the class les. Use this option to separate
.java and .class les.
-source Sets the source level. Valid values are 1.3, 1.4, 1.5, 1.6, 5, 6
-deprecation Gives detail information about the use of deprecated features
-Xlint:unchecked Gives detail information about unchecked type conversion warnings
Option Purpose
-cp or -classpath Sets the class path, used to search for class les. See the previous
table for details. Note that javac can succeed when java fails if the
current directory is on the source path but not the class path.
-ea or
-enableassertions
Enable assertions. By default, assertions are disabled.
-Dproperty=value Sets a system property that can be retrieved by System.
getProperty(String)
-jar Runs a program contained in a JAR le whose manifest has a
Main-Class entry. When this option is used, the class path is ignored.
-verbose Shows the classes that are loaded. This option may be useful to
debug class loading problems.
-Xmssize
-Xmxsize
Sets the initial or maximum heap size. The size is a value in bytes.
Add a sufx k or m for kilobytes or megabytes, for example, -Xmx10m
Want More? Download Now. Subscribe at refcardz.com
Design Patterns
Published June 2008
FREE
Upcoming Refcardz:
n
Agile Methodologies:
Best Practices
n
Core CSS: Part II
n
Spring Annotations
n
PHP
n
JUnit
n
SOA Patterns
n
Core CSS: Part III
n
Scalability and High Availability
n
MySQL
n
Seam
Available:
Published July 2008
n
NetBeans IDE 6.1 Java Editor
n
RSS and Atom
n
GlassFish Application Server
n
Silverlight 2
n
IntelliJ IDEA
Published June 2008
n
jQuerySelectors
n
Flexible Rails: Flex 3 on Rails 2
Published May 2008
n
Windows PowerShell
n
Dependency Injection in EJB 3
Published September 2008
n
Getting Started with JPA
n
JavaServer Faces
n
Struts2
n
Core CSS: Part I
Published August 2008
n
Core .NET
n
Very First Steps in Flex
n
C#
n
Groovy
Visit http://refcardz.dzone.com for a complete listing of available Refcardz.