Java Core
Java Core
JAVA KEYWORDS
Keyword abstract Description an abstract class or method Example abstract class Writable { public abstract void write(Writer out); public void save(String filename) { ... } } assert param != null; //Note: Run with -ea to enable assertions int boolean more = false; interface import instanceof more = true; implements defines the interface(s) that a class implements imports a package tests if an object is an instance of a class the 32-bit integer type class Student implements Printable { ... } import java.util.ArrayList; import com.dzone.refcardz.*; if (fred instanceof Student) value = ((Student) fred).getId(); //Note: null instanceof T is always false int value = 0; assert with assertions enabled, throws an error if condition not fulfilled the Boolean type with values true and false breaks out of a switch or loop
boolean
break
while ((ch = in.next()) != -1) { if (ch == '\n') break; process(ch); } // Note: Also see switch byte b = -1; // Not the same as 0xFF Note: Be careful with bytes < 0 see switch see try
interface Printable { void print(); } an abstract type with methods that a class can implement the 64-bit long integer type a method implemented by the host system allocates a new object or array a null reference a package of classes a feature that is accessible only by methods of this class a feature that is accessible only by methods of this class, its children, and other classes in the same package a feature that is accessible by methods of all classes returns from a method the 16-bit integer type a feature that is unique to its class, not to objects of its class Person fred = new Person("Fred"); Person optional = null; package com.dzone.refcardz; see class long worldPopulation = 6710044745L;
long native
byte
the 8-bit integer type a case of a switch the clause of a try block catching an exception the Unicode character type defines a class type
case catch
char class
char input = 'Q'; class Person { private String name; public Person(String aName) { name = aName; } public void print() { System.out.println(name); } }
private
protected
const continue
not used continues at the end of a loop while ((ch = in.next()) != -1) { if (ch == ' ') continue; process(ch); } see switch Do { ch = in.next(); } while (ch == ' '); double oneHalf = 0.5;
public
see class
int getId() { return id; } short skirtLength = 24; public class WriteUtil { public static void write(Writable[] ws, String filename); public static final String DEFAULT_EXT = ".dat"; }
default do
the default clause of a switch the top of a do/while loop the doubleprecision floatingnumber type the else clause of an if statement an enumerated type defines the parent class of a class
double
see if enum Mood { SAD, HAPPY }; class Student extends Person { private int id; public Student(String name, int anId) { ... } public void print() { ... } } public static final int DEFAULT_ID = 0;
strictfp
Use strict rules for floating-point computations invoke a superclass constructor or method public Student(String name, int anId) { super(name); id = anId; } public void print() { super.print(); System.out.println(id); } switch (ch) { case 'Q': case 'q': more = false; break; case ' '; break; default: process(ch); break; } Note: If you omit a break, processing continues with the next case. public synchronized void addGrade(String gr) { grades.add(gr); } public Student(String id) { this.id = id; } public Student() { this(""); }
super
final
a constant, or a class or method that cannot be overridden the part of a try block that is always executed the single-precision floating-point type a loop type
switch
a selection statement
finally
see try
float for
see try 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 after the : must be an array or an Iterable
synchronize d
a method or code block that is atomic to a thread the implicit argument of a method, or a constructor of this class
this
goto if
throws an exception
the exceptions that public void print() throws a method can throw PrinterException, IOException marks data that should not be persistent a block of code that traps exceptions class Student { private transient Data cachedData; } Try { try { fred.print(out); } catch (PrinterException ex) { ex.printStackTrace(); } } finally { out.close(); } public void print() { ... }
PRIMITIVE TYPES
Type int Size 4 bytes Range 2,147,483,648 to 2,147,483, 647 (just over 2 billion) Notes The wrapper type is Integer. Use BigInteger for arbitrary precision integers.
try
short long
2 bytes 8 bytes
32,768 to 32,767 9,223,372,036,854, 775,808 to 9,223,372,036,854, 775,807 128 to 127 approximately 3.40282347E+38F (67 significant decimal digits) approximately 1.7976931348623 1570E+308 (15 significant decimal digits) \u0000 to \uFFFF Literals end with L (e.g. 1L).
byte float
1 byte 4 bytes
void
denotes a method that returns no value ensures that a field is coherently accessed by multiple threads a loop
Note that the range is not 0 ... 255. Literals end with F (e.g. 0.5F)
volatile
class Student { private volatile int nextId; ... } while (in.hasNext()) process(in.next());
double
8 bytes
while
Use BigDecimal for arbitrary precision floating-point numbers. The wrapper type is Character. Unicode characters > U+FFFF require two char values.
char
2 bytes
boolean
OPERATOR PRECEDENCE
Operators with the same precedence [] . () (method call) ! ~ ++ -- + (unary) */% Left to right Right to left Left to right ~ flips each bit of a number Be careful when using % with negative numbers. -a % b == -(a % b), but a % -b == a % b. For example, -7 % 4 == -3, 7 % -4 == 3. Notes
Left to right Left to right >> is arithmetic shift (n >> 1 == n / 2 for positive and negative numbers), >>> is logical shift (adding 0 to the highest bits). The right hand side is reduced modulo 32 if the left hand side is an int or modulo 64 if the left hand side is a long. For example, 1 << 35 == 1 << 3. null instanceof T is always false Checks for identity. Use equals to check for structural equality. Bitwise AND; no lazy evaluation with bool arguments Bitwise XOR Bitwise OR; no lazy evaluation with bool
Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left
HashSet TreeSet EnumSet LinkedHashSet PriorityQueue HashMap TreeMap EnumMap LinkedHashMap WeakHashMap IdentityHashMa p
Common Tasks
List<String> strs = new ArrayList<String>(); strs.add("Hello"); strs.add("World!"); for (String str : strs) System.out.println(str); Iterator<String> iter = strs.iterator(); while (iter.hasNext()) { String str = iter.next(); if (someCondition(str)) iter.remove(); } strs.addAll(strColl); strs.addAll(Arrays.asList(args)) Collect strings Add strings Do something with all elements in the collection Remove elements that match a condition. The remove methodremoves the element returned by the preceding call to next. Add all strings from another collection of strings Add all strings from an array of strings. Arrays.asList makes a List wrapper for an array Remove all elements of another collection. Uses equals for comparison Get or set an element at a specified index Insert or remove an element at a specified index, shifting the elements with higher index values Convert from collection to array Convert from array to list. Use the varargs form to make a small collection. Sort a list by the natural order of the elements, or with a custom comparator.
Adds leading zeroes Left-justifies field Encloses negative number in parentheses Adds group separators Always includes a decimal point Adds 0x or 0 prefix Specifies the index of the argument to be formatted; for example, %1$d %1$x prints the first argument in decimal and hexadecimal Formats the same value as the previous specification; for example, %d %<x prints the same number in decimal and hexadecimal
strs.removeAll(coll);
if (0 <= i && i < strs.size()) { str = strs.get(i); strs.set(i, "Hello"); } strs.insert(i, "Hello"); str = strs.remove(i);
<
159 9F
Conversions Character
Conversion Character d x o f e g Description Decimal integer Hexadecimal integer Octal integer Fixed-point floating-point Exponential floating-point General floating-point (the shorter of e and f) 0x1.fccdp3 Hexadecimal floating-point s c b h String Character boolean boolean Hash code separator Date and time The percent symbol The platform-dependent line separator Hello H TRUE 42628b2 See the next table Example 159 9f 237 15.9 1.59E+001
String[] arr = new String[strs.size()]; strs.toArray(arr); String[] arr = ...; List<String> lst = Arrays.asList(arr); lst = Arrays.asList("foo", "bar", "baz"); List<String> lst = ...; lst.sort(); lst.sort(new Comparator<String>() { public int compare(String a, String b) { return a.length() - b.length(); 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 Iterate through all entries of the map
for (Map.Entry<String, Person> entry : map.entrySet()) { String key = entry.getKey(); Person value = entry.getValue(); Person key = map.get(str); // null if not found map.put(key, value);
tx % n
Yields "On January 1, 1999, a hurricane caused $100,000,000 of damage" -The nth item is denoted by {n,format,subformat} with optional formats and subformats shown below \ -{0} is the first item -The following table shows the available formats -Use single quotes for quoting, for example '{' for a literal left curly brace -Use '' for a literal single quote
Format number SubFormat none integer currency percent date none or medium short Example 1234.57 1235 $1,234.57 123457.00% -Jan 15, 2009 01/15/09 -January 15, 2009 -Thursday, January 15, 2009
Each format specifier has the following form. See the tables for flags and conversion characters
Flags
Flags + space Description Prints sign for positive and negative numbers Adds a space before positive numbers Example 3333.33 | 3333.33|
long full
time
03:45:00 PM 03:45:00 PM 3:45:00 PM PST 3:45:00 PM PST no house one house 5 houses
Optional X X, 0 or more times X, 1 or more times X n times, at least n times, between n and m times
choice
List of choices, separated by |. Each choice has - a lower bound (use -\u221Efor -oo) - a relational operator: < for less than, # or \u2264 for <= - a message format string For example, {1,choice,0#no houses|1#one house| 2#{1} houses}
Quantifier Suffixes
? + Turn default (greedy) match into reluctant match Turn default (greedy) match into reluctant match
REGULAR EXPRESSIONS
Common Tasks
String[] words = str.split("\\s+"); Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(str); String result = matcher.replaceAll("#"); Pattern pattern = Pattern.compile("[0-9]+"); Matcher matcher = pattern.matcher(str); while (matcher.find()) { 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)); } Find all groups (indicated by parentheses in the pattern). Here we find the hours and minutes in a date. Split a string along white space boundaries Replace all matches. Here we replace all digit sequences with a #. Find all matches.
Set Operations
XY X |Y Any string from X, followed by any string from Y Any string from X or Y
Grouping
(X) \g Capture the string matching X as a group The match of the gth group
Escapes
\c \Q . . . \E (? . . . ) The character c (must not be an alphabetic character) Quote . . . verbatim Special constructsee API notes of Pattern class
Punct ASCII Cntrl Blank Space javaLowerCase javaUpperCase javaWhitespace javaMirrored InBlock Category or InCategory
Character Classes
[C1C2. . .] Union: Any of the characters represented by C1C2, . . . The Ci are characters, character ranges c1-c2, or character classes. Example: [a-zA-Z0-9] Complement: Characters not represented by any of C1C2 , . . . Example: [^0-9] Intersection: Characters represented by all of C1C2 , . . . Example: [A-f&&[^G-'|]]
Boundary Matchers
^$ \b \B \A \z \Z \G Beginning, end of input (or beginning, end of line in multiline mode) A word boundary A nonword boundary Beginning of input End of input End of input except final line terminator End of previous match
Quantifiers
LOGGING
Common Tasks
Logger logger = Logger.getLogger("com.mycompany.myprog.my category"); logger.info("Connection successful."); Get a logger for a category Logs a message of level FINE. Available levels are SEVERE, WARNING,INFO,CONFIG,FINE, Logs the stack trace of a Throwable Sets the logging level to FINE. By default, the logging level is INFO, and less severe logging messages are not logged. Adds a file handler for saving the log records in a file. See the table below for the naming pattern. This handler uses a simple formatter instead of the XML formatter that is the default for file handlers. java.util.logging. FileHandler.append
/ %t %h %g %u %%
Path separator System temporary directory Value of user.home system property The generation number of rotated logs A unique number for resolving naming conflicts The % character
The default append mode for file loggers; true to append to an existing log file
FALSE
PROPERTY FILES
Contain name/value pairs, separated by =, :, or whitespace Whitespace around the name or before the start of the value is ignored 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. \t \n \f \r \\ \uxxxx escapes are recognized (but not \b or octal escapes) Files are assumed to be encoded in ISO 8859-1; use native2ascii to encode non-ASCII characters into Unicode escapes 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
The logging configuration can be configured through a logging configuration file, by default jre/lib/logging.properties. Another file can be specified with the system property java. util.logging.config.file when starting the virtual machine. (Note that the LogManager runs before main.)
Configuration Property loggerName.level Description The logging level of the logger by the given name Default None; the logger inherits the handler from its parent java.util.loggin g. ConsoleHandler
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. A whitespace or comma-separated list of class names for the given logger false if the parent logger's handlers (and ultimately the root logger's handlers) should not be used A whitespace or comma-separated list of class names for initialization. The default handler level
loggerName.handlers
None
loggerName. useParenthandlers
TRUE
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");
config
None
JAR FILES
Used for storing applications, code libraries By default, class files and other resources are stored in ZIP file format META-INF/MANIFEST.MF contains JAR metadata META-INF/services can contain service provider configuration Use the jar utility to make JAR file
java.util.logging. FileHandler.level java.util.logging. ConsoleHandler.level java.util.logging. FileHandler.formatter java.util.logging. ConsoleHandler.format ter java.util.logging. FileHandler.formatter java.util.logging. ConsoleHandler.format ter
java.util.loggin g. XMLFormatter for FileHandler, java.util.loggin g. SimpleFormatter for ConsoleHandler default platform encoding
i m M t u v
The default number of rotated log files The default naming pattern for log files. The following tokens are replaced when the file is created: Token Description
Extracts files. If you supply one or more file names, only those files are extracted. Otherwise, all files are extracted.
Jar xf myprog.jar
O Stores without ZIP compression
-sourcepath
OTHER
Heap just guarantees that elements on higher levels are greater (for max-heap) or smaller (for min-heap) than elements on lower levels, whereas BST guarantees order (from "left" to "right"). If you want sorted elements, go with BST.
5)
Equals and hashCode contract in Java: And equals method in Java must follow its contract with hashCode method in Java as stated below. 1) If two objects are equal by equals() method then there hashcode must be same. 2) If two objects are not equal by equals() method then there hashcode could be same or different. - If the variable(var) is byte, char, short or int, then var_code = (int)var; - - If the variable(var) is long, then var_code = (int)(var ^ (var >>> 32)); - If the variable(var) is float, then var_code = Float.floatToIntBits(var); - If the variable(var) is double, then -long bits = Double.doubleToLongBits(var);var_code = (int)(bits ^ (bits >>> 32)); - If the variable(var) is boolean, then var_code = var ? 1 : 0; - If the variable(var) is an object reference, then check if it is null, if yes then var_code = 0; otherwise invoke the hashCode method recursively on this object reference to get the hash code. This can be simplified and given as -var_code = (null == var ? 0 : var.hashCode());
public int hashCode(){ int hash = 7; hash = 31 * hash + num;