Refcardz Core Java PDF
Refcardz Core Java PDF
com
tech facts at your fingertips
CONTENTS INCLUDE:
Core Java
n
Java Keywords
n
Standard Java Packages
n
Character Escape Sequences
n
Collections and Common Algorithms
n
Regular Expressions
By Cay S. Horstmann
n
JAR Files
as well as the most commonly used tools (javac, java, jar). for a loop type for (int i = 10; i >= 0; i--)
System.out.println(i);
for (String s : line.split("\\s+"))
System.out.println(s);
Note: In the “generalized” for loop, the expression
Java Keywords after the : must be an array or an Iterable
goto not used
Keyword Description Example if a conditional statement if (input == 'Q')
System.exit(0);
abstract an abstract class or abstract class Writable { else
method public abstract void write(Writer out); more = true;
public void save(String filename) { ... }
implements defines the interface(s) class Student
} implements Printable {
that a class implements
...
assert with assertions enabled, assert param != null; }
throws an error if Note: Run with -ea to enable assertions
condition not fulfilled import imports a package import java.util.ArrayList;
import com.dzone.refcardz.*;
boolean the Boolean type with boolean more = false;
instanceof tests if an object is an if (fred instanceof Student)
values true and false value = ((Student) fred).getId();
instance of a class
break breaks out of a switch while ((ch = in.next()) != -1) { Note: null instanceof T is always false
or loop if (ch == '\n') break;
process(ch); int the 32-bit integer type int value = 0;
}
interface an abstract type with interface Printable {
Note: Also see switch methods that a class can void print();
www.dzone.com
}
byte the 8-bit integer type byte b = -1; // Not the same as 0xFF implement
Note: Be careful with bytes < 0 long the 64-bit long integer long worldPopulation = 6710044745L;
type
case a case of a switch see switch
native a method implemented
catch the clause of a try block see try by the host system
catching an exception
new allocates a new object Person fred = new Person("Fred");
char the Unicode character char input = 'Q'; or array
type
null a null reference Person optional = null;
class defines a class type class Person {
package a package of classes package com.dzone.refcardz;
private String name;
public Person(String aName) { private a feature that is see class
name = aName;
accessible only by
}
public void print() { methods of this class
System.out.println(name);
}
protected a feature that is accessible class Student {
only by methods of this protected int id;
} ...
class, its children, and
}
const not used other classes in the same
package →
continue continues at the end of while ((ch = in.next()) != -1) {
a loop if (ch == ' ') continue;
process(ch);
}
super invoke a superclass public Student(String name, int anId) { << >> >>> Left to right >> is arithmetic shift (n >> 1 == n / 2 for
constructor or method super(name); id = anId; positive and negative numbers), >>> is logical
}
shift (adding 0 to the highest bits). The right
public void print() { hand side is reduced modulo 32 if the left hand
super.print(); side is an int or modulo 64 if the left hand side
System.out.println(id);
}
is a long. For example, 1 << 35 == 1 << 3.
switch a selection statement switch (ch) { < <= > >= instanceof Left to right null instanceof T is always false
case 'Q':
case 'q': == != Left to right Checks for identity. Use equals to check for
more = false; break;
structural equality.
case ' ';
break;
default:
& Left to right Bitwise AND; no lazy evaluation with bool
process(ch); break; arguments
}
Note: If you omit a break, processing continues ^ Left to right Bitwise XOR
with the next case.
| Left to right Bitwise OR; no lazy evaluation with bool
synchronized a method or code public synchronized void addGrade(String gr) { arguments
block that is atomic to grades.add(gr);
a thread && Left to right
}
this the implicit argument public Student(String id) {this.id = id;} || Left to right
of a method, or a public Student() { this(""); }
constructor of this class ?: Right to left
throw throws an exception if (param == null) = += -= *= /= %= &= Right to left
throw new IllegalArgumentException(); |= ^= <<= >>= >>>=
throws the exceptions that a public void print()
method can throw throws PrinterException, IOException
ArrayList An indexed sequence that grows and shrinks dynamically Typical usage
LinkedList An ordered sequence that allows efficient insertions and removal at
any location System.out.printf("%4d %8.2f", quantity, price);
ArrayDeque A double-ended queue that is implemented as a circular array String str = String.format("%4d %8.2f", quantity, price);
HashSet An unordered collection that rejects duplicates Each format specifier has the following form. See the tables for
TreeSet A sorted set flags and conversion characters.
EnumSet A set of enumerated type values
LinkedHashSet A set that remembers the order in which elements were inserted
PriorityQueue A collection that allows efficient 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 Flags
IdentityHashMap A map with keys that are compared by ==, not equals
Flag Description Example
+ Prints sign for positive and negative numbers +3333.33
Common Tasks
space Adds a space before positive numbers | 3333.33|
List<String> strs = new ArrayList<String>(); Collect strings
0 Adds leading zeroes 003333.33
strs.add("Hello"); strs.add("World!"); Add strings
- Left-justifies field |3333.33 |
for (String str : strs) System.out.println(str); Do something with all elements
in the collection
( Encloses negative number in parentheses (3333.33)
Map<String, Person> map = new Make a map that is traversed in h Hash code 42628b2
LinkedHashMap<String, Person>(); insertion order (requires hashCode tx Date and time See the next table
for key type). Use a TreeMap to
traverse in sort order (requires that % The percent symbol %
key type is comparable). n The platform-dependent line separator
for (Map.Entry<String, Person> entry : Iterate through all entries of the
map.entrySet()) { map
String key = entry.getKey();
Person value = entry.getValue();
... Formatted output with MessageFormat
}
Person key = map.get(str); // null if not found Get or set a value for a given key
map.put(key, value); Typical usage:
String msg = MessageFormat.format("On {1, date,
long}, a {0} caused {2,number,currency} of damage.",
Character escape sequences "hurricane", new GregorianCalendar(2009, 0, 15).
getTime(), 1.0E8);
\b backspace \u0008
\t tab \u0009
Yields "On January 1, 1999, a hurricane caused
\n newline \u000A $100,000,000 of damage"
form feed \u000C n The nth item is denoted by {n,format,subformat} with
\f
\r carriage return \u000D
optional formats and subformats shown below
\" double quote
n {0} is the first item
\' single quote
n The following table shows the available formats
\\ backslash
\uhhhh (hhhh is a hex number between 0000 and FFFF) The UTF-16 code point with value hhhh n Use single quotes for quoting, for example '{' for a literal
\ooo (ooo is an octal number between 0 and 377) The character with octal value ooo left curly brace
Note: Unlike in C/C++, \xhh is not allowed n Use '' for a literal single quote
→
currency $1,234.57
\B A nonword boundary
percent 123,457%
\A Beginning of input
\z End of input
date none or medium Jan 15, 2009
\Z End of input except final line terminator
short 1/15/09
\G End of previous match
long January 15, 2009
Quantifiers
full Thursday, January 15, 2009
X? Optional X
time none or medium 3:45:00 PM
X* X, 0 or more times
short 3:45 PM
X+ X, 1 or more times
long 3:45:00 PM PST
X{n} X{n,} X{n,m} X n times, at least n times, between n and m times
full 3:45:00 PM PST
Quantifier Suffixes
choice List of choices, separated by |. Each choice has no house
? Turn default (greedy) match into reluctant match
n a lower bound (use -\u221E for -∞)
\s A whitespace character [ \t\n\r\f\x0B] UNIX_LINES Only '\n' is recognized as a line terminator when matching ^
and $ in multiline mode.
\S A nonwhitespace character
DOTALL When using this flag, the . symbol matches all characters,
\w A word character [a-zA-Z0-9_] including line terminators.
\W A nonword character CANON_EQ Takes canonical equivalence of Unicode characters into account.
For example, u followed by ¨ (diaeresis) matches ü.
\p{name} A named character class—see table below
LITERAL The input string that specifies the pattern is treated as a sequence
\P{name} The complement of a named character class of literal characters, without special meanings for . [ ] etc.
Logger logger = Get a logger for a category n Whitespace around the name or before the start of the
Logger.getLogger("com.mycompany.myprog.mycategory");
logger.info("Connection successful."); Logs a message of level FINE.
value is ignored
Available levels are SEVERE, n Lines can be continued by placing an \ as the last character;
WARNING,INFO,CONFIG,FINE,
FINER, FINEST, with leading whitespace on the continuation line is ignored
corresponding methods severe,
warning, and so on. button1.tooltip = This is a long \
logger.log(Level.SEVERE, "Unexpected exception", Logs the stack trace of a tooltip text.
throwable); Throwable
logger.setLevel(Level.FINE); Sets the logging level to FINE. n \t \n \f \r \\ \uxxxx escapes are recognized (but not \b
By default, the logging level is
INFO, and less severe logging
or octal escapes)
messages are not logged. n Files are assumed to be encoded in ISO 8859-1; use
Handler handler = new FileHandler("%h/myapp.log", Adds a file handler for saving the
SIZE_LIMIT, LOG_ROTATION_COUNT); log records in a file. See the table
native2ascii to encode non-ASCII characters into
handler.setFormatter(new SimpleFormatter()); below for the naming pattern. This Unicode escapes
logger.addHandler(handler); handler uses a simple formatter
n Blank lines and lines starting with # or ! are ignored
instead of the XML formatter that
IntelliJ IDEA
n
n
DZone, Inc.
1251 NW Maynard
ISBN-13: 978-1-934238-26-4
Cary, NC 27513
ISBN-10: 1-934238-26-0
50795
888.678.0399
DZone communities deliver over 3.5 million pages per month to 919.678.0300
more than 1.5 million software developers, architects and designers.
Refcardz Feedback Welcome
DZone offers something for every developer, including news, refcardz@dzone.com
$7.95
tutorials, blogs, cheatsheets, feature articles, source code and more. Sponsorship Opportunities 9 781934 238264
“DZone is a developer’s dream,” says PC Magazine. 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, Version 1.0
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.