rc024 Corejava PDF
rc024 Corejava PDF
rc024 Corejava PDF
C O NT E NT S
024
Core Java
Java Keywords
Standard Java Packages
Lambda Expressions
Collections & Common Algorithms
Character Escape Sequences,
and more...
A B O U T CO R E J AVA
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).
KEYWORD
DESCRIPTION
EX AMPLE
default
(cont.)
2) denotes default
implementation
of an interface
method
public interface
Collection<E> {
@Override
default Spliterator<E>
spliterator() {
return Spliterators.
spliterator(this, 0);
}
}
do
do {
ch = in.next();
} while (ch == ' ');
double
else
see if
enum
an enumerated type
extends
final
a constant, or a
class or method
that cannot be
overridden
finally
the part of a
try block that is
always executed
see try
float
J AVA K E Y W O R DS
KEYWORD
DESCRIPTION
EX AMPLE
abstract
an abstract class
or method
with assertions
enabled, throws
an error if condition
not fulfilled
boolean
break
breaks out of a
switch or loop
assert
case
a case of a switch
see switch
catch
see try
char
the Unicode
character type
class
defines a class
type
class Person {
private String name;
public Person(String
aName) {
name = aName;
}
public void print() {
System.out.
println(name);
}
}
C O R E JAVA
continue
continues at the
end of a loop
default
1) the default
clause of a switch
see switch
D Z O NE, INC.
DZ O NE .C O M
CORE JAVA
KEYWORD
DESCRIPTION
EX AMPLE
KEYWORD
DESCRIPTION
for
a loop type
strictfp
super
invoke a superclass
constructor or
method
switch
a selection
statement
switch (ch) {
case 'Q':
case 'q':
more = false; break;
case ' ';
break;
default:
process(ch); break;
}
a conditional
statement
if (input == 'Q')
System.exit(0);
else
more = true;
implements
defines the
interface(s) that a
class 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 value = 0;
interface
an abstract type
with methods that a
class can implement
interface Printable {
void print();
}
long
long worldPopulation =
6710044745L;
native
a method
implemented by the
host system
new
allocates a new
object or array
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
a feature that is
accessible only by
methods of this
class, its children,
and other classes in
the same package
class Student {
protected int id;
...
}
public
a feature that is
accessible by
methods of all classes
see class
return
returns from a
method
short
static
a feature that is
unique to its class,
not to objects of its
class
D Z O NE, INC .
EX AMPLE
synchronized
a method or code
block that is atomic
to a thread
this
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();
}
void
denotes a method
that returns no value
volatile
ensures that a
field is coherently
accessed by
multiple threads
class Student {
private volatile int
nextId;
...
}
while
a loop
while (in.hasNext())
process(in.next());
S TA N DA R D J AVA PAC K A G E S
java.applet
java.awt
DZ O NE.C O M
CORE JAVA
java.beans
java.io
TYPE
SIZE
R ANGE
NOTES
int
4 bytes
2,147,483,648 to 2,147,483,
647
( just over 2 billion)
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)
Use BigDecimal
for arbitrary
precision floatingpoint numbers
char
2 bytes
\u0000 to \uFFFF
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.time
java.util
O P E R AT O R P R E C E D E N C E
OPER ATORS WITH THE SAME
PRECEDENCE
NOTES
[] . ()
Left to right
! ~ ++ -- +
(unary) (unary)
() (cast) new
Right to left
* / %
Left to right
+ -
Left to right
Left to right
Left to right
== !=
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
(method call)
boolean
true or false
-4 == 3
L A M B DA E X P R E S S I O N S
FUNCTIONAL INTERFACES
Interfaces with a single abstract method. Example:
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
D Z O NE, INC .
DZ O NE.C O M
CORE JAVA
COMMON TASKS
Collect strings
strs.add("Hello"); strs.
add("World!");
Add strings
strs.addAll(strColl);
list.forEach(element ->
System.out.println(element));
strs.addAll(Arrays.asList(args))
strs.removeAll(coll);
strs.insert(i, "Hello");
str = strs.remove(i);
METHOD REFERENCES
Lambda expressions represent anonymous functions. You can
pass them as method parameters or return them. The same can be
done with named methods using method references.
Typical usage of method references:
WITHOUT METHOD REFERENCE
list.forEach(System.
out::println);
EX AMPLE
To a static method
Collections::emptyList
user::getFirstName
User::getFirstName
To a constructor
User::new
CO L L E C T I O N S & CO M M O N A LG O R I T H M S
ArrayList
LinkedList
ArrayDeque
HashSet
TreeSet
A sorted set
EnumSet
LinkedHashSet
PriorityQueue
HashMap
TreeMap
EnumMap
LinkedHashMap
WeakHashMap
IdentityHashMap
D Z O NE, INC .
strs.forEach(System.out::println);
DZ O NE.C O M
5
String concat = strs
.stream()
.collect(Collectors.joining(", "));
Combine operations
This will not result in
two traversals of the list
elements
Simple reduction
operation
CORE JAVA
FLAGS
FLAG
DESCRIPTION
EX AMPLE
+3333.33
space
| 3333.33|
003333.33
Left-justifies field
|3333.33 |
(3333.33)
3,333.33
# (for f
3,333.
# (for x or
o format)
Adds 0x or 0 prefix
0xcafe
159 9F
<
159 9F
format)
CONVERSION CHARACTERS
C H A R AC T E R E S C A P E S E Q U E N C E S
\b
backspace \u0008
CONVERSION
CHARACTER
DESCRIPTION
EX AMPLE
Decimal integer
159
Hexadecimal integer
9f
Octal integer
237
\t
tab \u0009
\n
newline \u000A
Fixed-point floating-point
15.9
\f
Exponential floating-point
1.59e+01
\r
\"
double quote
Hexadecimal floating-point
0x1.fccdp3
\'
single quote
String
Hello
\\
backslash
Character
boolean
true
Hash code
42628b2
tx
F O R M AT T E D O U T P U T W I T H P R I N T F
TYPICAL USAGE
System.out.printf("%4d %8.2f", quantity, price);
String str = String.format("%4d %8.2f", quantity, price);
Each format specifier has the following form. See the tables for
flags and conversion characters.
D Z O NE, INC .
DZ O NE.C O M
CORE JAVA
Use single quotes for quoting, for example '{' for a literal left
curly brace
\cc
FORMAT
SUBFORMAT
EX AMPLE
number
none
1,234.567
[C1C2 ...]
integer
1,235
currency
$1,234.57
percent
123,457%
none or medium
short
1/15/15
long
January 15,
2015
full
Thursday,
January 15,
2015
none or medium
3:45:00 PM
short
date
time
choice
[^C1C2 ...]
[C1&&C2&& ...]
3:45 PM
\d
A digit [0-9]
long
3:45:00 PM PST
\D
A nondigit [^0-9]
full
3:45:00 PM PST
no houses
\s
\S
A nonwhitespace character
\w
\W
A nonword character
\p{name}
\P{name}
one house
5 houses
BOUNDARY MATCHERS
REGUL AR EXPRESSIONS
COMMON TASKS
String[] words = str.split("\\s+");
^ $
\b
A word boundary
\B
A nonword boundary
\A
Beginning of input
\z
End of input
\Z
\G
QUANTIFIERS
X?
Optional X
X*
X, 0 or more times
X+
X, 1 or more times
X{n} X{n,}
X{n,m}
QUANTIFIER SUFFIXES
The character c
\unnnn, \xnn,
\0n, \0nn,
\0nnn
D Z O NE, INC .
XY
X|Y
DZ O NE.C O M
CORE JAVA
GROUPING
FLAG
DESCRIPTION
(X)
CANON_EQ
\g
LITERAL
ESCAPES
\c
\Q ... \E
Quote . . . verbatim
(? ... )
LO G G I N G
COMMON TASKS
Lower
Upper
Alpha
Digit
Alnum
XDigit
Print or Graph
Punct
ASCII
Cntrl
Blank
Space
Whitespace [ \t\n\r\f\0x0B]
javaLowerCase
javaUpperCase
javaWhitespace
javaMirrored
Mirrored, as determined by
InBlock
Category or
InCategory
Character.isLowerCase()
Character.isUpperCase()
Character.isMirrored()
CASE_INSENSITIVE
logger.info("Connection
successful.");
logger.log(Level.SEVERE,
"Unexpected exception",
Throwable);
logger.setLevel(Level.
FINE);
Character.isWhitespace()
FLAG
Logger logger =
Logger.getLogger("com.
mycompany.myprog.
mycategory");
CONFIGURATION
PROPERTY
DESCRIPTION
DEFAULT
loggerName.level
handlers
java.util.logging.
ConsoleHandler
loggerName.
handlers
None
UNICODE_CASE
MULTILINE
loggerName.
useParentHandlers
true
config
None
D Z O NE, INC .
DZ O NE.C O M
CORE JAVA
CONFIGURATION
PROPERTY
DESCRIPTION
DEFAULT
java.util.logging.
FileHandler.level
Level.ALL for
FileHandler,
Level.INFO for
ConsoleHandler
java.util.logging.
ConsoleHandler.
level
java.util.logging.
FileHandler.filter
Typical usage:
Properties props = new Properties();
props.load(new FileInputStream("prog.properties"));
String value = props.getProperty("button1.tooltip");
// null if not present
None
java.util.logging.
XMLFormatter for
FileHandler,
java.util.logging.
SimpleFormatter
for ConsoleHandler
default platform
encoding
java.util.logging.
ConsoleHandler.
filter
java.util.logging.
FileHandler.
formatter
java.util.logging.
ConsoleHandler.
formatter
java.util.logging.
FileHandler.
encoding
JAR FILES
java.util.logging.
ConsoleHandler.
encoding
java.util.logging.
FileHandler.limit
logging.properties
java.util.logging.
FileHandler.count
java.util.logging.
FileHandler.
pattern
%h/java%u.log
DESCRIPTION
Extracts files. If you supply one or more file names, only those
files are extracted. Otherwise, all files are extracted
java.util.logging.
FileHandler.
append
TOKEN
DESCRIPTION
Path seperator
%t
%h
%g
%u
%%
The % character
P RO P E R T Y F I L E S
jar xf myprog.jar
D Z O NE, INC .
DZ O NE.C O M
CORE JAVA
CO M M O N J AVAC O P T I O N S
CO M M O N J AVA O P T I O N S
OPTION
DESCRIPTION
OPTION
DESCRIPTION
-cp or -classpath
-cp or -classpath
-ea or
-enableassertions
-Dproperty=value
-jar
-verbose
-Xmssize
-Xmxsize
-sourcepath
-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, 1.7, 1.8, 5, 6, 7, 8
-deprecation
-Xlint:unchecked
System.getProperty(String)
CREDITS:
Editor: G. Ryan Spain | Designer: Yassee Mohebbi | Production: Chris Smith | Sponsor Relations: Chris Brumfield | Marketing: Chelsea Bosworth
COMMUNITIES:
Share links, author articles, and engage with other tech experts
JOIN NOW
DZONE, INC.
150 PRESTON EXECUTIVE DR.
CARY, NC 27513
DZone communities deliver over 6 million pages each month to more than 3.3 million software
developers, architects and decision makers. DZone offers something for everyone, including news,
tutorials, cheat sheets, research guides, feature articles, source code and more.
888.678.0399
919.678.0300
REFCARDZ FEEDBACK WELCOME
[email protected]
Copyright 2015 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any
DZONE,
DZONE, INC.
INC.
form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
SPONSORSHIP OPPORTUNITIES
DZONE.COM
DZONE.COM
[email protected]
VERSION 1.0
$7.95