Java Cheat Sheet
Java Cheat Sheet
Java Keywords
Regular Expressions
JAR Files
Core Java
By Cay S. Horstmann
Java Keywords, continued
Example
see try
float
the single-precision
floating-point type
for
a loop type
Keyword
Description
Example
abstract
an abstract class or
method
boolean
break
assert
www.dzone.com
Description
finally
Java Keywords
goto
not used
if
a conditional statement
if (input == 'Q')
System.exit(0);
else
more = true;
implements
class Student
implements Printable {
...
}
import
imports a package
import java.util.ArrayList;
import com.dzone.refcardz.*;
instanceof
tests if an object is an
instance of a class
int
int value = 0;
interface
interface Printable {
void print();
}
long
native
a method implemented
by the host system
new
a case of a switch
see switch
catch
see try
char
class
class Person {
private String name;
public Person(String aName) {
name = aName;
}
public void print() {
System.out.println(name);
}
}
Core Java
Keyword
null
a null reference
package
a package of classes
package com.dzone.refcardz;
private
a feature that is
accessible only by
methods of this class
see class
protected
class Student {
protected int id;
...
}
const
not used
continue
default
see switch
do
do {
ch = in.next();
} while (ch == ' ');
double
the double-precision
floating-number type
else
see if
enum
an enumerated type
extends
final
a constant, or a class or
method that cannot be
overridden
Authoritative content
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
}
public static final int DEFAULT_ID = 0;
DZone, Inc.
www.dzone.com
Core Java
Operator Precedence
Keyword
Description
Example
public
a feature that is
accessible by methods
of all classes
see class
return
short
static
a feature that is
unique to its class, not
to objects of its class
strictfp
super
invoke a superclass
constructor or method
Notes
(method call)
Left to right
! ~ ++ -- + (unary)
(unary) () (cast) new
Right to left
* / %
Left to right
+ -
Left to right
Left to right
switch (ch) {
case 'Q':
case 'q':
more = false; break;
case ' ';
break;
default:
process(ch); break;
}
Left to right
null instanceof T
== !=
Left to right
&
Left to right
Left to right
Bitwise XOR
Left to right
&&
Left to right
||
Left to right
?:
Right to left
= += -= *= /= %= &=
|= ^= <<= >>= >>>=
Right to left
[] . ()
switch
a selection statement
a method or code
block that is atomic to
a thread
throw
throws an exception
if (param == null)
throw new IllegalArgumentException();
throws
transient
class Student {
private transient Data cachedData;
...
}
try
try {
try {
fred.print(out);
} catch (PrinterException ex) {
ex.printStackTrace();
}
} finally {
out.close();
}
synchronized
this
grades.add(gr);
}
void
denotes a method
that returns no value
volatile
class Student {
private volatile int nextId;
...
}
a loop
while (in.hasNext())
while
Primitive types
process(in.next());
java.awt
java.beans
java.io
java.lang
Language support
java.math
Arbitrary-precision numbers
java.net
Networking
java.nio
java.rmi
java.security
Security support
java.sql
Database support
java.text
java.util
is always false
Type
Size
Range
Notes
int
4 bytes
short
2 bytes
32,768 to 32,767
long
8 bytes
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
byte
1 byte
128 to 127
float
4 bytes
approximately
3.40282347E+38F (67
significant decimal digits)
double
8 bytes
approximately
1.79769313486231570E+308
(15 significant decimal digits)
char
2 bytes
\u0000
boolean
true
to \uFFFF
or false
DZone, Inc.
www.dzone.com
Core Java
LinkedList
ArrayDeque
HashSet
TreeSet
A sorted set
EnumSet
LinkedHashSet
PriorityQueue
HashMap
TreeMap
EnumMap
LinkedHashMap
WeakHashMap
IdentityHashMap
Each format specifier has the following form. See the tables for
flags and conversion characters.
Flags
Common Tasks
List<String> strs = new ArrayList<String>();
Collect strings
strs.add("Hello"); strs.add("World!");
Add strings
strs.addAll(strColl);
strs.addAll(Arrays.asList(args))
strs.removeAll(coll);
strs.insert(i, "Hello");
str = strs.remove(i);
Description
Example
+3333.33
space
| 3333.33|
003333.33
Left-justifies field
|3333.33 |
(3333.33)
3,333.33
3,333.
# (for x or o
format)
Adds 0x or 0 prefix
0xcafe
159 9F
<
159 9F
Conversion characters
Conversion
Character
Description
Example
Decimal integer
159
Hexadecimal integer
9f
Octal integer
237
Fixed-point floating-point
15.9
Exponential floating-point
1.59e+01
Hexadecimal floating-point
0x1.fccdp3
String
Hello
Character
boolean
true
Hash code
42628b2
tx
backspace \u0008
\t
tab \u0009
\n
newline \u000A
\f
\r
\"
double quote
\'
single quote
\\
backslash
\ooo (ooo
Flag
DZone, Inc.
www.dzone.com
Core Java
Format
Subformat
Example
Boundary Matchers
number
none
1,234.567
^ $
integer
1,235
\b
A word boundary
currency
$1,234.57
\B
A nonword boundary
percent
123,457%
\A
Beginning of input
none or medium
\z
End of input
short
1/15/09
\Z
\G
date
time
choice
long
full
none or medium
3:45:00 PM
short
3:45 PM
long
3:45:00 PM PST
full
3:45:00 PM PST
no house
Quantifiers
X?
Optional X
X*
X, 0 or more times
X+
X, 1 or more times
Quantifier Suffixes
?
one house
5 houses
Set Operations
XY
X |Y
Grouping
Regular Expressions
(X)
\g
Escapes
Common Tasks
String[] words = str.split("\\s+");
\c
\Q . . . \E
Quote . . . verbatim
(? . . . )
Upper
while (matcher.find()) {
Alpha
Digit
Alnum
process(str.substring(matcher.start(), matcher.end()));
}
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));
The character c
\unnnn, \xnn,
\0n, \0nn,
\0nnn
The control characters tab, newline, return, form feed, alert, and escape
\cc
Character Classes
[C1C 2 . . .]
[^C1C2 . . .]
[C1&& C2 && . . .]
Any character except line terminators (or any character if the DOTALL
flag is set)
\d
A digit [0-9]
\D
or Graph
Punct
ASCII
Cntrl
Blank
Space
Whitespace [ \t\n\r\f\0x0B]
javaLowerCase
javaUpperCase
javaWhitespace
javaMirrored
InBlock
Category or InCategory
XDigit
Flag
Description
CASE_INSENSITIVE
UNICODE_CASE
A nondigit [^0-9]
MULTILINE
^ and $ match the beginning and end of a line, not the entire input.
\s
UNIX_LINES
\S
A nonwhitespace character
DOTALL
\w
\W
A nonword character
CANON_EQ
\p{name}
\P{name}
LITERAL
DZone, Inc.
www.dzone.com
Core Java
Property files
LOGGING
Common Tasks
Logger logger =
Logger.getLogger("com.mycompany.myprog.mycategory");
logger.info("Connection successful.");
Throwable
throwable);
n
n
n
logger.setLevel(Level.FINE);
Description
Default
handlers
java.util.logging.
ConsoleHandler
loggerName.handlers
None
loggerName.
false
true
config
None
java.util.logging.
FileHandler.level
Level.ALL for
FileHandler,
Level.INFO for
ConsoleHandler
None
java.util.logging.
XMLFormatter for
FileHandler,
java.util.logging.
SimpleFormatter for
ConsoleHandler
useParenthandlers
java.util.logging.
ConsoleHandler.level
java.util.logging.
FileHandler.formatter
java.util.logging.
ConsoleHandler.formatter
java.util.logging.
FileHandler.encoding
JAR Files
Used for storing applications, code libraries
By default, class files and other resources are stored in
ZIP file format
n META-INF/MANIFEST.MF contains JAR metadata
Description
Creates a new or empty archive and adds files to it. If any of the specified file
names are directories, the jar program processes them recursively.
default platform
encoding
java.util.logging.
ConsoleHandler.encoding
java.util.logging.
FileHandler.limit
java.util.logging.
FileHandler.count
java.util.logging.
FileHandler.pattern
Specifies the JAR file name as the second command-line argument. If this
parameter is missing, jar will write the result to standard output (when creating a
JAR file) or read it from standard input (when extracting or tabulating a JAR file).
logging.properties
java.util.logging.
FileHandler.append
java.util.logging.
ConsoleHandler.formatter
java.util.logging.
FileHandler.formatter
or octal escapes)
Files are assumed to be encoded in ISO 8859-1; use
native2ascii to encode non-ASCII characters into
Unicode escapes
Typical usage:
Configuration Property
%h/java%u.log
Token
Description
Path separator
%t
%h
%g
%u
%%
The % character
Extracts files. If you supply one or more file names, only those files are
extracted. Otherwise, all files are extracted.
jar xf myprog.jar
DZone, Inc.
www.dzone.com
Core Java
or -classpath
-sourcepath
Purpose
Option
Sets the class path, used to search for class files. The class path is a
list of directories, JAR files, or expressions of the form directory/'*'
(Unix) or directory\* (Windows). The latter refers to all JAR files
in the given directory. Class path items are separated by : (Unix)
or ; (Windows). If no class path is specified, it is set to the current
directory. If a class path is specified, the current directory is not
automatically includedadd a . item if you want to include it.
-cp
Purpose
or -classpath
-ea or
-enableassertions
-Dproperty=value
Sets the path used to search for source files. If source and class files
are present for a given file, the source is compiled if it is newer. If no
source path is specified, it is set to the current directory.
-d
Sets the path used to place the class files. Use this option to separate
.java and .class files.
-source
Sets the source level. Valid values are 1.3, 1.4, 1.5, 1.6, 5, 6
-deprecation
-Xlint:unchecked
Sets the class path, used to search for class files. 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.
Enable assertions. By default, assertions are disabled.
Sets a system property that can be retrieved by System.
getProperty(String)
-jar
-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 suffix k or m for kilobytes or megabytes, for example, -Xmx10m
R E C O MM E N D E D B O O K S
Cay S. Horstmann
Cay S. Horstmann has written many books on C++, Java and objectoriented 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 office 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
n
n
Web Site
Blog
http://horstmann.com
http://weblogs.java.net/blog/cayhorstmann
BUY NOW
books.dzone.com/books/corejava1
books.dzone.com/books/corejava2
Core .NET
Equinox
Spring Annotations
C#
EMF
Core Java
Groovy
XML
Struts2
PHP
JavaServer Faces
Silverlight 2
FREE
Design Patterns
Published June 2008
DZone, Inc.
1251 NW Maynard
Cary, NC 27513
ISBN-13: 978-1-934238-26-4
ISBN-10: 1-934238-26-0
50795
888.678.0399
919.678.0300
Refcardz Feedback Welcome
[email protected]
Sponsorship Opportunities
[email protected]
$7.95
Core Seam
9 781934 238264
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