SlideShare uma empresa Scribd logo
1 de 6
Baixar para ler offline
#24
                                                                                                                                                                                           tech facts at your fingertips
  Get More Refcardz! Visit refcardz.com


                                          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


                                                                                                                                               Java Keywords, continued
                                                  AbOUT CORE JAVA
                                                                                                                                               Keyword      Description                    Example
                                                                                                                                               finally      the part of a try block        see try
                                                 This refcard gives you an overview of key aspects of the Java                                              that is always executed
                                                 language and cheat sheets on the core library (formatted                                      float        the single-precision           float oneHalf = 0.5F;
                                                 output, collections, regular expressions, logging, properties)                                             floating-point type

                                                 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);
                                                                                        }

                                                 default    the default clause of a
                                                            switch
                                                                                        see switch                                                                                     Get More Refcardz
                                                                                                                                                                                                  (They’re free!)
                                                 do         the top of a do/while       do {
                                                            loop                          ch = in.next();
                                                                                        } while (ch == ' ');                                                                           n   Authoritative content
                                                 double     the double-precision        double oneHalf = 0.5;                                                                          n   Designed for developers
                                                            floating-number type
                                                                                                                                                                                       n   Written by top experts
                                                 else       the else clause of an if    see if
                                                            statement                                                                                                                  n   Latest tools & technologies
Core Java




                                                 enum       an enumerated type          enum Mood { SAD, HAPPY };                                                                      n   Hot tips & examples
                                                 extends    defines the parent class    class Student extends Person {
                                                                                                                                                                                       n   Bonus content online
                                                                                          private int id;
                                                            of a class
                                                                                          public Student(String name, int anId) { ... }
                                                                                                                                                                                       n   New issue every 1-2 weeks
                                                                                          public void print() { ... }
                                                                                        }
                                                                                                                                                                 Subscribe Now for FREE!
                                                 final      a constant, or a class or   public static final int DEFAULT_ID = 0;
                                                            method that cannot be                                                                                     Refcardz.com
                                                            overridden



                                                                                                                            DZone, Inc.   |   www.dzone.com
2
                                                                                                                                                                                          Core Java
       tech facts at your fingertips




Java Keywords, continued
                                                                                                          OpERATOR pRECEDENCE
Keyword            Description                 Example
public             a feature that is           see class
                   accessible by methods                                                                 Operators with the                          Notes
                   of all classes                                                                        same precedence
return             returns from a method       int getId() { return id; }                                [] . () (method call)       Left to right
short              the 16-bit integer type     short skirtLength = 24;
                                                                                                         ! ~ ++ -- + (unary) –       Right to left   ~ flips each bit of a number
static             a feature that is           public class WriteUtil {                                  (unary) () (cast) new
                   unique to its class, not      public static void write(Writable[] ws,
                                                   String filename);                                     * / %                       Left to right   Be careful when using % with negative
                   to objects of its class
                                                 public static final String DEFAULT_EXT = ".dat";                                                    numbers. -a % b == -(a % b), but a
                                               }
                                                                                                                                                     % -b == a % b. For example, -7 % 4
strictfp           Use strict rules                                                                                                                  == -3, 7 % -4 == 3.
                   for floating-point
                   computations                                                                          + -                         Left to right

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

transient          marks data that should      class Student {
                                                 private transient Data cachedData;
                                                                                                             pRImITIVE TypES
                   not be persistent
                                                 ...
                                               }
                                                                                                         Type        Size        Range                                 Notes
try                a block of code that        try {
                   traps exceptions              try {
                                                    fred.print(out);
                                                                                                         int         4 bytes      –2,147,483,648 to 2,147,483, 647     The wrapper type is Integer.
                                                 } catch (PrinterException ex) {                                                 (just over 2 billion)                 Use BigInteger for arbitrary
                                                    ex.printStackTrace();                                                                                              precision integers.
                                                 }
                                               } finally {                                               short       2 bytes     –32,768 to 32,767
                                                 out.close();
                                               }                                                         long        8 bytes     –9,223,372,036,854,775,808 to         Literals end with L (e.g. 1L).
void               denotes a method            public void print() { ... }                                                       9,223,372,036,854,775,807
                   that returns no value                                                                 byte        1 byte      –128 to 127                           Note that the range is not
volatile           ensures that a field is     class Student {                                                                                                         0 ... 255.
                   coherently accessed         private volatile int nextId;
                   by multiple threads         ...                                                       float       4 bytes     approximately                         Literals end with F (e.g. 0.5F)
                                               }                                                                                 ±3.40282347E+38F (6–7
while              a loop                      while (in.hasNext())                                                              significant decimal digits)
                                                   process(in.next());                                   double      8 bytes     approximately                         Use BigDecimal for arbitrary
                                                                                                                                 ±1.79769313486231570E+308             precision floating-point
                                                                                                                                 (15 significant decimal digits)       numbers.
 STANDARD JAVA pACKAgES                                                                                  char        2 bytes     u0000 to uFFFF                      The wrapper type is
                                                                                                                                                                       Character. Unicode
java.applet           Applets (Java programs that run inside a web page)                                                                                               characters > U+FFFF require
                                                                                                                                                                       two char values.
java.awt              Graphics and graphical user interfaces
                                                                                                         boolean                 true or false
java.beans            Support for JavaBeans components (classes with properties and
                      event listeners)
java.io               Input and output
                                                                                                         Legal conversions between primitive types
                                                                                                         Dotted arrows denote conversions that may lose precision.
java.lang             Language support
java.math             Arbitrary-precision numbers
java.net              Networking
java.nio              “New” (memory-mapped) I/O
java.rmi              Remote method invocations
java.security         Security support
java.sql              Database support
java.text             Internationalized formatting of text and numbers
java.util             Utilities (including data structures, concurrency, regular expressions,
                      and logging)



                                                                                    DZone, Inc.     |   www.dzone.com
3
                                                                                                                                                                                    Core Java
     tech facts at your fingertips




  COLLECTIONS AND COmmON ALgORIThmS                                                                      FORmATTED OUTpUT wITh printf

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)

Iterator<String> iter = strs.iterator();                Remove elements that match a
                                                                                                     ,               Adds group separators                                        3,333.33
while (iter.hasNext()) {                                condition. The remove method
   String str = iter.next();
                                                                                                     # (for f format) Always includes a decimal point                             3,333.
   if (someCondition(str)) iter.remove();
                                                        removes the element returned by
                                                        the preceding call to next.                  # (for x or o   Adds 0x or 0 prefix                                          0xcafe
}
                                                                                                     format)
strs.addAll(strColl);                                   Add all strings from another
                                                        collection of strings
                                                                                                     $               Specifies the index of the argument to be formatted;         159 9F
                                                                                                                     for example, %1$d %1$x prints the first argument in
strs.addAll(Arrays.asList(args))                        Add all strings from an array of                             decimal and hexadecimal
                                                        strings. Arrays.asList makes a
                                                        List wrapper for an array
                                                                                                     <               Formats the same value as the previous specification;        159 9F
                                                                                                                     for example, %d %<x prints the same number in decimal
strs.removeAll(coll);                                   Remove all elements of another                               and hexadecimal
                                                        collection. Uses equals for
                                                        comparison
                                                                                                     Conversion characters
if (0 <= i && i < strs.size()) {                        Get or set an element at a
  str = strs.get(i);                                    specified index
  strs.set(i, "Hello");                                                                              Conversion      Description                                       Example
}                                                                                                    Character
strs.insert(i, "Hello");                                Insert or remove an element at               d               Decimal integer                                   159
str = strs.remove(i);                                   a specified index, shifting the              x               Hexadecimal integer                               9f
                                                        elements with higher index values
                                                                                                     o               Octal integer                                     237
String[] arr = new String[strs.size()];                 Convert from collection to array
strs.toArray(arr);                                                                                   f               Fixed-point floating-point                        15.9
String[] arr = ...;                                     Convert from array to list. Use              e               Exponential floating-point                        1.59e+01
List<String> lst = Arrays.asList(arr);                  the varargs form to make a small
lst = Arrays.asList("foo", "bar", "baz");                                                            g               General floating-point (the shorter of e and f)
                                                        collection.
List<String> lst = ...;                                 Sort a list by the natural order of          a               Hexadecimal floating-point                        0x1.fccdp3
lst.sort();                                             the elements, or with a custom
lst.sort(new Comparator<String>() {                                                                  s               String                                            Hello
  public int compare(String a, String b) {
                                                        comparator.
     return a.length() - b.length();                                                                 c               Character                                         H
  }
}
                                                                                                     b               boolean                                           true

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"
f                                                    form feed u000C                               	      n   The nth item is denoted by {n,format,subformat} with
r                                                    carriage return u000D
                                                                                                                optional formats and subformats shown below
"                                                    double quote
                                                                                                     	      n   {0} is the first item
'                                                    single quote
                                                    backslash
                                                                                                     	      n   The following table shows the available formats
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                           →

                                                                                DZone, Inc.     |   www.dzone.com
4
                                                                                                                                                                                                Core Java
     tech facts at your fingertips




Formatted Output with MessageFormat, continued                                                                  Regular Expression Syntax, continued
Format          Subformat                                                    Example                            Boundary Matchers
number          none                                                         1,234.567                          ^ $                   Beginning, end of input (or beginning, end of line in multiline mode)

                integer                                                      1,235                              b                    A word boundary

                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 -∞)


                         n		a relational operator: < for “less than”, # or
                                                                             one house                          +                     Turn default (greedy) match into reluctant match
                            u2264 for ≤                                                                        Set Operations
                                                                             5 houses
                         n a message format string
                                                                                                                XY                    Any string from X, followed by any string from Y
                For example, {1,choice,0#no houses|1#one
                                                                                                                X |Y                  Any string from X or Y
                house|2#{1} houses}
                                                                                                                Grouping
                                                                                                                (X)                   Capture the string matching X as a group
    REgULAR ExpRESSIONS                                                                                         g                    The match of the gth group
                                                                                                                Escapes
Common Tasks                                                                                                    c                    The character c (must not be an alphabetic character)
                                                                                                                Q . . . E           Quote . . . verbatim
String[] words = str.split("s+");                                           Split a string along white
                                                                              space boundaries                  (? . . . )            Special construct— see API notes of Pattern class
Pattern pattern = Pattern.compile("[0-9]+");                                  Replace all matches.
Matcher matcher = pattern.matcher(str);                                       Here we replace all digit         Predefined Character Class Names
String result = matcher.replaceAll("#");                                      sequences with a #.
                                                                                                                Lower                       ASCII lower case [a-z]
Pattern pattern = Pattern.compile("[0-9]+");                                  Find all matches.
Matcher matcher = pattern.matcher(str);                                                                         Upper                       ASCII upper case [A-Z]
while (matcher.find()) {                                                                                        Alpha                       ASCII alphabetic [A-Za-z]
    process(str.substring(matcher.start(), matcher.end()));
}
                                                                                                                Digit                       ASCII digits [0-9]
                                                                                                                Alnum                       ASCII alphabetic or digit [A-Za-z0-9]
Pattern pattern = Pattern.compile(                                            Find all groups (indicated
 "(1?[0-9]):([0-5][0-9])[ap]m");                                              by parentheses in the             XDigit                      Hex digits [0-9A-Fa-f]
Matcher matcher = pattern.matcher(str);                                       pattern). Here we find
                                                                                                                Print or Graph              Printable ASCII character [x21-x7E]
                                                                              the hours and minutes
for (int i = 1; i <= matcher.groupCount(); i++) {
                                                                              in a date.                        Punct                       ASCII nonalpha or digit [p{Print}&&P{Alnum}]
     process(matcher.group(i));
}
                                                                                                                ASCII                       All ASCII [x00-x7F]
                                                                                                                Cntrl                       ASCII Control character [x00-x1F]
Regular Expression Syntax                                                                                       Blank                       Space or tab [ t]
                                                                                                                Space                       Whitespace [ tnrf0x0B]
Characters
                                                                                                                javaLowerCase               Lower case, as determined by Character.isLowerCase()
c                         The character c
                                                                                                                javaUpperCase               Upper case, as determined by Character.isUpperCase()
unnnn, xnn,             The code unit with the given hex or octal value
0n, 0nn,                                                                                                      javaWhitespace              White space, as determined by Character.isWhiteSpace()
0nnn
                                                                                                                javaMirrored                Mirrored, as determined by Character.isMirrored()
t, n, r,               The control characters tab, newline, return, form feed, alert, and escape
                                                                                                                InBlock                     Block is the name of a Unicode character block, with spaces
f, a, e
                                                                                                                                            removed, such as BasicLatin or Mongolian.
cc                       The control character corresponding to the character c
                                                                                                                Category or InCategory      Category is the name of a Unicode character category such
Character Classes                                                                                                                           as L (letter) or Sc (currency symbol).
[C1C 2 . . .]             Union: Any of the characters represented by C1C 2 , . . .
                          The Ci are characters, character ranges c1-c 2, or character classes.                 Flags for matching
                          Example: [a-zA-Z0-9_]
                                                                                                                The pattern matching can be adjusted with flags, for example:
[^C1C2 . . .]             Complement: Characters not represented by any of C1C 2 , . . .
                          Example: [^0-9]                                                                       Pattern pattern = Pattern.compile(patternString,
[C1&& C2 && . . .]        Intersection: Characters represented by all of C1C 2 , . . .                            Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE)
                          Example: [A-f&&[^G-`]]
                                                                                                                Flag                     Description
Predefined Character Classes
                                                                                                                CASE_INSENSITIVE         Match characters independently of the letter case. By default,
.                         Any character except line terminators (or any character if the DOTALL                                          this flag takes only US ASCII characters into account.
                          flag is set)
                                                                                                                UNICODE_CASE             When used in combination with CASE_INSENSITIVE, use Unicode
d                        A digit [0-9]                                                                                                  letter case for matching.
D                        A nondigit [^0-9]                                                                     MULTILINE                ^ and $ match the beginning and end of a line, not the entire input.

s                        A whitespace character [ tnrfx0B]                                                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.



                                                                                            DZone, Inc.    |   www.dzone.com
5
                                                                                                                                                                                                     Core Java
    tech facts at your fingertips




 LOggINg                                                                                                             pROpERTy FILES

Common Tasks                                                                                                 	        n   Contain name/value pairs, separated by =, :, or whitespace
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);
                                                                                                                          native2ascii to encode non-ASCII characters into
                                                                 log records in a file. See the table
handler.setFormatter(new SimpleFormatter());                     below for the naming pattern. This                       Unicode escapes
logger.addHandler(handler);                                      handler uses a simple formatter
                                                                 instead of the XML formatter that           	        n   Blank lines and lines starting with # or ! are ignored
                                                                 is the default for file handlers.
                                                                                                             Typical usage:
Logging Configuration Files
                                                                                                             Properties props = new Properties();
The logging configuration can be configured through a logging
                                                                                                             props.load(new FileInputStream("prog.properties"));
configuration file, by default jre/lib/logging.properties.                                                   String value = props.getProperty("button1.tooltip");
Another file can be specified with the system property java.                                                 // null if not present
util.logging.config.file when starting the virtual machine.
(Note that the LogManager runs before main.)                                                                 Also used for resource bundles:
                                                                                                             ResourceBundle bundle = ResourceBundle.getBundle("prog");
Configuration Property        Description                                      Default
                                                                                                                // Searches for prog_en_US.properties,
loggerName.level              The logging level of the logger by the           None; the logger
                              given name                                       inherits the handler             // prog_en.properties, etc.
                                                                               from its parent               String value = bundle.getString("button1.tooltip");
handlers                      A whitespace or comma-separated list             java.util.logging.
                              of class names for the root logger. An           ConsoleHandler
                              instance is created for each class name,
                              using the default constructor.
                                                                                                                     JAR FILES
loggerName.handlers           A whitespace or comma-separated list             None
                              of class names for the given logger                                            	        n   Used for storing applications, code libraries
loggerName.                   false if the parent logger's handlers            true
useParenthandlers             (and ultimately the root logger's
                                                                                                             	        n   By default, class files and other resources are stored in
                              handlers) should not be used                                                                ZIP file format
config                        A whitespace or comma-separated list             None
                              of class names for initialization.
                                                                                                             	        n   META-INF/MANIFEST.MF contains JAR metadata
java.util.logging.            The default handler level                        Level.ALL for                          n   META-INF/services can contain service provider
FileHandler.level                                                              FileHandler,
                                                                               Level.INFO for
                                                                                                                          configuration
java.util.logging.
ConsoleHandler.level                                                           ConsoleHandler                	        n   Use the jar utility to make JAR files
java.util.logging.            The class name of the default filter             None
FileHandler.formatter
java.util.logging.
                                                                                                             jar Utility Options
ConsoleHandler.formatter
                                                                                                                 Option     Description
java.util.logging.            The class name of the default formatter          java.util.logging.
FileHandler.formatter                                                          XMLFormatter for                  c          Creates a new or empty archive and adds files to it. If any of the specified file
java.util.logging.                                                             FileHandler,                                 names are directories, the jar program processes them recursively.
ConsoleHandler.formatter                                                       java.util.logging.
                                                                                                                 C          Temporarily changes the directory. For example,
                                                                               SimpleFormatter for
                                                                               ConsoleHandler                               jar cvfC myprog.jar classes *.class
                                                                                                                            changes to the classes subdirectory to add class files.
java.util.logging.            The default encoding                             default platform
FileHandler.encoding                                                           encoding                          e          Creates a Main-Class entry in the manifest
java.util.logging.                                                                                                          jar cvfe myprog.jar com.mycom.mypkg.MainClass files
ConsoleHandler.encoding
                                                                                                                 f          Specifies the JAR file name as the second command-line argument. If this
java.util.logging.            The default limit for rotating log files,        0 (No limit), but set                        parameter is missing, jar will write the result to standard output (when creating a
FileHandler.limit             in bytes                                         to 50000 in jre/lib/                         JAR file) or read it from standard input (when extracting or tabulating a JAR file).
                                                                               logging.properties
                                                                                                                 i          Creates an index file (for speeding up lookups in a large archive)
java.util.logging.            The default number of rotated log files          1
FileHandler.count                                                                                                m          Adds a manifest to the JAR file.
java.util.logging.            The default naming pattern for log files.        %h/java%u.log                                jar cvfm myprog.jar mymanifest.mf files
FileHandler.pattern           The following tokens are replaced when
                              the file is created:
                                                                                                                 M          Does not create a manifest file for the entries.

                               Token   Description                                                               t          Displays the table of contents.
                               /       Path separator                                                                       jar tvf myprog.jar

                               %t      System temporary directory                                                u          Updates an existing JAR file
                               %h      Value of user.home system property                                                   jar uf myprog.jar com/mycom/mypkg/SomeClass.class
                               %g      The generation number of rotated logs                                     v          Generates verbose output.
                               %u      A unique number for resolving
                                       naming conflicts                                                          x          Extracts files. If you supply one or more file names, only those files are
                               %%      The % character                                                                      extracted. Otherwise, all files are extracted.
                                                                                                                            jar xf myprog.jar
java.util.logging.            The default append mode for file loggers; false
FileHandler.append            true to append to an existing log file                                             O          Stores without ZIP compression



                                                                                         DZone, Inc.    |   www.dzone.com
6
                                                                                                                                                                                                                           Core Java
              tech facts at your fingertips




          COmmON javac OpTIONS                                                                                                      COmmON java OpTIONS

         Option                   Purpose                                                                                          Option                     Purpose
         -cp or -classpath        Sets the class path, used to search for class files. The class path is a                         -cp or -classpath          Sets the class path, used to search for class files. See the previous
                                  list of directories, JAR files, or expressions of the form directory/'*'                                                    table for details. Note that javac can succeed when java fails if the
                                  (Unix) or directory* (Windows). The latter refers to all JAR files
                                                                                                                                                              current directory is on the source path but not the class path.
                                  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                          -ea or                     Enable assertions. By default, assertions are disabled.
                                  directory. If a class path is specified, the current directory is not                            -enableassertions
                                  automatically included—add a . item if you want to include it.
                                                                                                                                   -Dproperty=value           Sets a system property that can be retrieved by System.
         -sourcepath              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                                                  getProperty(String)
                                  source path is specified, it is set to the current directory.
                                                                                                                                   -jar                       Runs a program contained in a JAR file whose manifest has a
         -d                       Sets the path used to place the class files. Use this option to separate                                                    Main-Class entry. When this option is used, the class path is ignored.
                                  .java and .class files.
                                                                                                                                   -verbose                   Shows the classes that are loaded. This option may be useful to
         -source                  Sets the source level. Valid values are 1.3, 1.4, 1.5, 1.6, 5, 6                                                            debug class loading problems.
         -deprecation             Gives detail information about the use of deprecated features
                                                                                                                                   -Xmssize                   Sets the initial or maximum heap size. The size is a value in bytes.
         -Xlint:unchecked         Gives detail information about unchecked type conversion warnings                                -Xmxsize                   Add a suffix k or m for kilobytes or megabytes, for example, -Xmx10m




   AbOUT ThE AUThOR                                                                                                                                RECOmmENDED bOOKS

                               Cay S. Horstmann                                                                                                                                                                   Core Java, now in
                               Cay S. Horstmann has written many books on C++, Java and object-
                                                                                                                                                                                                                  its 8th edition, is a
                               oriented development, is the series editor for Core Books at Prentice-Hall
                               and a frequent speaker at computer industry conferences. For four years,                                                                                                           no-nonsense tutorial
                               Cay was VP and CTO of an Internet startup that went from 3 people in a                                                                                                             and reliable reference
                               tiny office to a public company. He is now a computer science professor                                                                                                            into all aspects of
                               at San Jose State University. He was elected Java Champion in 2005.
                                                                                                                                                                                                                  Java SE 6.
   Publications
   n	   Core Java, with Gary Cornell (Sun Microsystems Press 1996–2007)
   n	   Core JavaServer Faces, with David Geary (Sun Microsystems Press 2004–2006)
   n	   Big Java (John Wiley & Sons 2001–2007)
                                                                                                                                                                                         bUy NOw
   Web Site                                         Blog                                                                                                          books.dzone.com/books/corejava1
   http://horstmann.com                             http://weblogs.java.net/blog/cayhorstmann                                                                     books.dzone.com/books/corejava2


Get More FREE Refcardz. Visit refcardz.com now!
                                                                Available:
Core Seam                                                       Essential Ruby                                       Core CSS: Part I

Core CSS: Part III                                              Essential MySQL                                      Struts2
                                                                JUnit and EasyMock                                   Core .NET
Hibernate Search
                                                                Getting Started with MyEclipse                       Very First Steps in Flex
                                                                                                                                                                                   FREE
Equinox                                                         Spring Annotations                                   C#
                                                                Core Java                                            Groovy
EMF
                                                                Core CSS: Part II                                    NetBeans IDE 6.1 Java Editor
XML
                                                                PHP                                                  RSS and Atom
JSP Expression Language                                         Getting Started with JPA                             GlassFish Application Server
ALM Best Practices                                              JavaServer Faces                                     Silverlight 2                                                                                Design Patterns
                                                                                                                                                                                                                Published June 2008
HTML and XHTML                                                  Visit refcardz.com for a complete listing of available Refcardz.



                                                                                                                            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 4 million pages each month to                                                               919.678.0300
 more than 1.7 million software developers, architects and decision                                                         Refcardz Feedback Welcome
 makers. DZone offers something for everyone, including news,                                                               refcardz@dzone.com
                                                                                                                                                                                                                                             $7.95




 tutorials, cheatsheets, blogs, 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.

Mais conteúdo relacionado

Mais procurados

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in JavaAbhilash Nair
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - OperatorsWebStackAcademy
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String FunctionsAvanitrambadiya
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascriptToan Nguyen
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structureSajid Marwat
 
Py.test
Py.testPy.test
Py.testsoasme
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 

Mais procurados (20)

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Servlets
ServletsServlets
Servlets
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
Php string function
Php string function Php string function
Php string function
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
Regular expression in javascript
Regular expression in javascriptRegular expression in javascript
Regular expression in javascript
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Java Strings
Java StringsJava Strings
Java Strings
 
Lec 17 heap data structure
Lec 17 heap data structureLec 17 heap data structure
Lec 17 heap data structure
 
Py.test
Py.testPy.test
Py.test
 
enums
enumsenums
enums
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 

Destaque

Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat SheetGlowTouch
 
Cheat sheet - String Java (Referência rápida)
Cheat sheet - String Java (Referência rápida)Cheat sheet - String Java (Referência rápida)
Cheat sheet - String Java (Referência rápida)Rafael Liberato
 
Bash Cheat Sheet -- Bash History Cheat Sheet
Bash Cheat Sheet -- Bash History Cheat SheetBash Cheat Sheet -- Bash History Cheat Sheet
Bash Cheat Sheet -- Bash History Cheat SheetPeter Krumins
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersSaeid Zebardast
 
Web Components Revolution
Web Components RevolutionWeb Components Revolution
Web Components RevolutionSaeid Zebardast
 
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!Noopur Gupta
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetAlexey Lesovsky
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Monica Beckwith
 
24 Books You've Never Heard Of - But Will Change Your Life
24 Books You've Never Heard Of - But Will Change Your Life24 Books You've Never Heard Of - But Will Change Your Life
24 Books You've Never Heard Of - But Will Change Your LifeRyan Holiday
 
20 Quotes To Turn Your Obstacles Into Opportunities
20 Quotes To Turn Your Obstacles Into Opportunities20 Quotes To Turn Your Obstacles Into Opportunities
20 Quotes To Turn Your Obstacles Into OpportunitiesRyan Holiday
 

Destaque (18)

Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Java cheat sheet
Java cheat sheetJava cheat sheet
Java cheat sheet
 
Cheat sheet - String Java (Referência rápida)
Cheat sheet - String Java (Referência rápida)Cheat sheet - String Java (Referência rápida)
Cheat sheet - String Java (Referência rápida)
 
MySQL Cheat Sheet
MySQL Cheat SheetMySQL Cheat Sheet
MySQL Cheat Sheet
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
Bash Cheat Sheet -- Bash History Cheat Sheet
Bash Cheat Sheet -- Bash History Cheat SheetBash Cheat Sheet -- Bash History Cheat Sheet
Bash Cheat Sheet -- Bash History Cheat Sheet
 
Developing Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginnersDeveloping Applications with MySQL and Java for beginners
Developing Applications with MySQL and Java for beginners
 
Web Components Revolution
Web Components RevolutionWeb Components Revolution
Web Components Revolution
 
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
Mastering your Eclipse IDE - Tips, Tricks, Java 8 tooling & More!
 
MySQL Cheat Sheet
MySQL Cheat SheetMySQL Cheat Sheet
MySQL Cheat Sheet
 
PostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication CheatsheetPostgreSQL Streaming Replication Cheatsheet
PostgreSQL Streaming Replication Cheatsheet
 
Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!Java 9: The (G1) GC Awakens!
Java 9: The (G1) GC Awakens!
 
24 Books You've Never Heard Of - But Will Change Your Life
24 Books You've Never Heard Of - But Will Change Your Life24 Books You've Never Heard Of - But Will Change Your Life
24 Books You've Never Heard Of - But Will Change Your Life
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
20 Quotes To Turn Your Obstacles Into Opportunities
20 Quotes To Turn Your Obstacles Into Opportunities20 Quotes To Turn Your Obstacles Into Opportunities
20 Quotes To Turn Your Obstacles Into Opportunities
 
Work Rules!
Work Rules!Work Rules!
Work Rules!
 

Semelhante a Cheat Sheet java

Corejava Online 100
Corejava Online 100Corejava Online 100
Corejava Online 100reynolds
 
Java Reference
Java ReferenceJava Reference
Java Referencekhoj4u
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceShalini Pillai
 
Java programming guide - quick reference
Java programming guide -  quick referenceJava programming guide -  quick reference
Java programming guide - quick referenceTutorials Tips Tricks
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceShalini Pillai
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceShalini Pillai
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick ReferenceFrescatiStory
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.Brian Hsu
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
Java常见疑惑和陷阱
Java常见疑惑和陷阱Java常见疑惑和陷阱
Java常见疑惑和陷阱Ady Liu
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answersKuntal Bhowmick
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, androidi i
 
Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...
Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...
Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...ICSM 2011
 
[A4]de view2012 scala-michinisougu
[A4]de view2012 scala-michinisougu[A4]de view2012 scala-michinisougu
[A4]de view2012 scala-michinisouguNAVER D2
 

Semelhante a Cheat Sheet java (20)

Corejava Online 100
Corejava Online 100Corejava Online 100
Corejava Online 100
 
Java Reference
Java ReferenceJava Reference
Java Reference
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20reference
 
Java programming guide - quick reference
Java programming guide -  quick referenceJava programming guide -  quick reference
Java programming guide - quick reference
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20reference
 
Java%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20referenceJava%20 programming%20guide%20 %20quick%20reference
Java%20 programming%20guide%20 %20quick%20reference
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick Reference
 
Scala
ScalaScala
Scala
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Java常见疑惑和陷阱
Java常见疑惑和陷阱Java常见疑惑和陷阱
Java常见疑惑和陷阱
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Java questions with answers
Java questions with answersJava questions with answers
Java questions with answers
 
imperative programming language, java, android
imperative programming language, java, androidimperative programming language, java, android
imperative programming language, java, android
 
Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...
Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...
Dynamic Analysis - SCOTCH: Improving Test-to-Code Traceability using Slicing ...
 
Intro to J Ruby
Intro to J RubyIntro to J Ruby
Intro to J Ruby
 
[A4]de view2012 scala-michinisougu
[A4]de view2012 scala-michinisougu[A4]de view2012 scala-michinisougu
[A4]de view2012 scala-michinisougu
 
20070329 Tech Study
20070329 Tech Study 20070329 Tech Study
20070329 Tech Study
 
First fare 2010 java-introduction
First fare 2010 java-introductionFirst fare 2010 java-introduction
First fare 2010 java-introduction
 

Mais de arkslideshareacc

The complete getting started guide to birt reporting 1 (1)
The complete getting started guide to birt reporting 1 (1)The complete getting started guide to birt reporting 1 (1)
The complete getting started guide to birt reporting 1 (1)arkslideshareacc
 
How to talk to your cfo with confidence eguide
How to talk to your cfo with confidence eguideHow to talk to your cfo with confidence eguide
How to talk to your cfo with confidence eguidearkslideshareacc
 

Mais de arkslideshareacc (6)

The complete getting started guide to birt reporting 1 (1)
The complete getting started guide to birt reporting 1 (1)The complete getting started guide to birt reporting 1 (1)
The complete getting started guide to birt reporting 1 (1)
 
How to talk to your cfo with confidence eguide
How to talk to your cfo with confidence eguideHow to talk to your cfo with confidence eguide
How to talk to your cfo with confidence eguide
 
Rc019 corecss1 online
Rc019 corecss1 onlineRc019 corecss1 online
Rc019 corecss1 online
 
Rc018 corenet online
Rc018 corenet onlineRc018 corenet online
Rc018 corenet online
 
Rc016 csharp online
Rc016 csharp onlineRc016 csharp online
Rc016 csharp online
 
Rc012 glassfish online
Rc012 glassfish onlineRc012 glassfish online
Rc012 glassfish online
 

Último

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 

Último (20)

Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 

Cheat Sheet java

  • 1. #24 tech facts at your fingertips Get More Refcardz! Visit refcardz.com 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 Java Keywords, continued AbOUT CORE JAVA Keyword Description Example finally the part of a try block see try This refcard gives you an overview of key aspects of the Java that is always executed language and cheat sheets on the core library (formatted float the single-precision float oneHalf = 0.5F; output, collections, regular expressions, logging, properties) floating-point type 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); } default the default clause of a switch see switch Get More Refcardz (They’re free!) do the top of a do/while do { loop ch = in.next(); } while (ch == ' '); n Authoritative content double the double-precision double oneHalf = 0.5; n Designed for developers floating-number type n Written by top experts else the else clause of an if see if statement n Latest tools & technologies Core Java enum an enumerated type enum Mood { SAD, HAPPY }; n Hot tips & examples extends defines the parent class class Student extends Person { n Bonus content online private int id; of a class public Student(String name, int anId) { ... } n New issue every 1-2 weeks public void print() { ... } } Subscribe Now for FREE! final a constant, or a class or public static final int DEFAULT_ID = 0; method that cannot be Refcardz.com overridden DZone, Inc. | www.dzone.com
  • 2. 2 Core Java tech facts at your fingertips Java Keywords, continued OpERATOR pRECEDENCE Keyword Description Example public a feature that is see class accessible by methods Operators with the Notes of all classes same precedence return returns from a method int getId() { return id; } [] . () (method call) Left to right short the 16-bit integer type short skirtLength = 24; ! ~ ++ -- + (unary) – Right to left ~ flips each bit of a number static a feature that is public class WriteUtil { (unary) () (cast) new unique to its class, not public static void write(Writable[] ws, String filename); * / % Left to right Be careful when using % with negative to objects of its class public static final String DEFAULT_EXT = ".dat"; numbers. -a % b == -(a % b), but a } % -b == a % b. For example, -7 % 4 strictfp Use strict rules == -3, 7 % -4 == 3. for floating-point computations + - Left to right 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 transient marks data that should class Student { private transient Data cachedData; pRImITIVE TypES not be persistent ... } Type Size Range Notes try a block of code that try { traps exceptions try { fred.print(out); int 4 bytes –2,147,483,648 to 2,147,483, 647 The wrapper type is Integer. } catch (PrinterException ex) { (just over 2 billion) Use BigInteger for arbitrary ex.printStackTrace(); precision integers. } } finally { short 2 bytes –32,768 to 32,767 out.close(); } long 8 bytes –9,223,372,036,854,775,808 to Literals end with L (e.g. 1L). void denotes a method public void print() { ... } 9,223,372,036,854,775,807 that returns no value byte 1 byte –128 to 127 Note that the range is not volatile ensures that a field is class Student { 0 ... 255. coherently accessed private volatile int nextId; by multiple threads ... float 4 bytes approximately Literals end with F (e.g. 0.5F) } ±3.40282347E+38F (6–7 while a loop while (in.hasNext()) significant decimal digits) process(in.next()); double 8 bytes approximately Use BigDecimal for arbitrary ±1.79769313486231570E+308 precision floating-point (15 significant decimal digits) numbers. STANDARD JAVA pACKAgES char 2 bytes u0000 to uFFFF The wrapper type is Character. Unicode java.applet Applets (Java programs that run inside a web page) characters > U+FFFF require two char values. java.awt Graphics and graphical user interfaces boolean true or false java.beans Support for JavaBeans components (classes with properties and event listeners) java.io Input and output Legal conversions between primitive types Dotted arrows denote conversions that may lose precision. java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio “New” (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.util Utilities (including data structures, concurrency, regular expressions, and logging) DZone, Inc. | www.dzone.com
  • 3. 3 Core Java tech facts at your fingertips COLLECTIONS AND COmmON ALgORIThmS FORmATTED OUTpUT wITh printf 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) Iterator<String> iter = strs.iterator(); Remove elements that match a , Adds group separators 3,333.33 while (iter.hasNext()) { condition. The remove method String str = iter.next(); # (for f format) Always includes a decimal point 3,333. if (someCondition(str)) iter.remove(); removes the element returned by the preceding call to next. # (for x or o Adds 0x or 0 prefix 0xcafe } format) strs.addAll(strColl); Add all strings from another collection of strings $ Specifies the index of the argument to be formatted; 159 9F for example, %1$d %1$x prints the first argument in strs.addAll(Arrays.asList(args)) Add all strings from an array of decimal and hexadecimal strings. Arrays.asList makes a List wrapper for an array < Formats the same value as the previous specification; 159 9F for example, %d %<x prints the same number in decimal strs.removeAll(coll); Remove all elements of another and hexadecimal collection. Uses equals for comparison Conversion characters if (0 <= i && i < strs.size()) { Get or set an element at a str = strs.get(i); specified index strs.set(i, "Hello"); Conversion Description Example } Character strs.insert(i, "Hello"); Insert or remove an element at d Decimal integer 159 str = strs.remove(i); a specified index, shifting the x Hexadecimal integer 9f elements with higher index values o Octal integer 237 String[] arr = new String[strs.size()]; Convert from collection to array strs.toArray(arr); f Fixed-point floating-point 15.9 String[] arr = ...; Convert from array to list. Use e Exponential floating-point 1.59e+01 List<String> lst = Arrays.asList(arr); the varargs form to make a small lst = Arrays.asList("foo", "bar", "baz"); g General floating-point (the shorter of e and f) collection. List<String> lst = ...; Sort a list by the natural order of a Hexadecimal floating-point 0x1.fccdp3 lst.sort(); the elements, or with a custom lst.sort(new Comparator<String>() { s String Hello public int compare(String a, String b) { comparator. return a.length() - b.length(); c Character H } } b boolean true 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" f form feed u000C n The nth item is denoted by {n,format,subformat} with r carriage return u000D optional formats and subformats shown below " double quote n {0} is the first item ' single quote backslash n The following table shows the available formats 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 → DZone, Inc. | www.dzone.com
  • 4. 4 Core Java tech facts at your fingertips Formatted Output with MessageFormat, continued Regular Expression Syntax, continued Format Subformat Example Boundary Matchers number none 1,234.567 ^ $ Beginning, end of input (or beginning, end of line in multiline mode) integer 1,235 b A word boundary 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 -∞) n a relational operator: < for “less than”, # or one house + Turn default (greedy) match into reluctant match u2264 for ≤ Set Operations 5 houses n a message format string XY Any string from X, followed by any string from Y For example, {1,choice,0#no houses|1#one X |Y Any string from X or Y house|2#{1} houses} Grouping (X) Capture the string matching X as a group REgULAR ExpRESSIONS g The match of the gth group Escapes Common Tasks c The character c (must not be an alphabetic character) Q . . . E Quote . . . verbatim String[] words = str.split("s+"); Split a string along white space boundaries (? . . . ) Special construct— see API notes of Pattern class Pattern pattern = Pattern.compile("[0-9]+"); Replace all matches. Matcher matcher = pattern.matcher(str); Here we replace all digit Predefined Character Class Names String result = matcher.replaceAll("#"); sequences with a #. Lower ASCII lower case [a-z] Pattern pattern = Pattern.compile("[0-9]+"); Find all matches. Matcher matcher = pattern.matcher(str); Upper ASCII upper case [A-Z] while (matcher.find()) { Alpha ASCII alphabetic [A-Za-z] process(str.substring(matcher.start(), matcher.end())); } Digit ASCII digits [0-9] Alnum ASCII alphabetic or digit [A-Za-z0-9] Pattern pattern = Pattern.compile( Find all groups (indicated "(1?[0-9]):([0-5][0-9])[ap]m"); by parentheses in the XDigit Hex digits [0-9A-Fa-f] Matcher matcher = pattern.matcher(str); pattern). Here we find Print or Graph Printable ASCII character [x21-x7E] the hours and minutes for (int i = 1; i <= matcher.groupCount(); i++) { in a date. Punct ASCII nonalpha or digit [p{Print}&&P{Alnum}] process(matcher.group(i)); } ASCII All ASCII [x00-x7F] Cntrl ASCII Control character [x00-x1F] Regular Expression Syntax Blank Space or tab [ t] Space Whitespace [ tnrf0x0B] Characters javaLowerCase Lower case, as determined by Character.isLowerCase() c The character c javaUpperCase Upper case, as determined by Character.isUpperCase() unnnn, xnn, The code unit with the given hex or octal value 0n, 0nn, javaWhitespace White space, as determined by Character.isWhiteSpace() 0nnn javaMirrored Mirrored, as determined by Character.isMirrored() t, n, r, The control characters tab, newline, return, form feed, alert, and escape InBlock Block is the name of a Unicode character block, with spaces f, a, e removed, such as BasicLatin or Mongolian. cc The control character corresponding to the character c Category or InCategory Category is the name of a Unicode character category such Character Classes as L (letter) or Sc (currency symbol). [C1C 2 . . .] Union: Any of the characters represented by C1C 2 , . . . The Ci are characters, character ranges c1-c 2, or character classes. Flags for matching Example: [a-zA-Z0-9_] The pattern matching can be adjusted with flags, for example: [^C1C2 . . .] Complement: Characters not represented by any of C1C 2 , . . . Example: [^0-9] Pattern pattern = Pattern.compile(patternString, [C1&& C2 && . . .] Intersection: Characters represented by all of C1C 2 , . . . Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE) Example: [A-f&&[^G-`]] Flag Description Predefined Character Classes CASE_INSENSITIVE Match characters independently of the letter case. By default, . Any character except line terminators (or any character if the DOTALL this flag takes only US ASCII characters into account. flag is set) UNICODE_CASE When used in combination with CASE_INSENSITIVE, use Unicode d A digit [0-9] letter case for matching. D A nondigit [^0-9] MULTILINE ^ and $ match the beginning and end of a line, not the entire input. s A whitespace character [ tnrfx0B] 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. DZone, Inc. | www.dzone.com
  • 5. 5 Core Java tech facts at your fingertips LOggINg pROpERTy FILES Common Tasks n Contain name/value pairs, separated by =, :, or whitespace 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); native2ascii to encode non-ASCII characters into log records in a file. See the table handler.setFormatter(new SimpleFormatter()); below for the naming pattern. This Unicode escapes logger.addHandler(handler); handler uses a simple formatter instead of the XML formatter that n Blank lines and lines starting with # or ! are ignored is the default for file handlers. Typical usage: Logging Configuration Files Properties props = new Properties(); The logging configuration can be configured through a logging props.load(new FileInputStream("prog.properties")); configuration file, by default jre/lib/logging.properties. String value = props.getProperty("button1.tooltip"); Another file can be specified with the system property java. // null if not present util.logging.config.file when starting the virtual machine. (Note that the LogManager runs before main.) Also used for resource bundles: ResourceBundle bundle = ResourceBundle.getBundle("prog"); Configuration Property Description Default // Searches for prog_en_US.properties, loggerName.level The logging level of the logger by the None; the logger given name inherits the handler // prog_en.properties, etc. from its parent String value = bundle.getString("button1.tooltip"); handlers A whitespace or comma-separated list java.util.logging. of class names for the root logger. An ConsoleHandler instance is created for each class name, using the default constructor. JAR FILES loggerName.handlers A whitespace or comma-separated list None of class names for the given logger n Used for storing applications, code libraries loggerName. false if the parent logger's handlers true useParenthandlers (and ultimately the root logger's n By default, class files and other resources are stored in handlers) should not be used ZIP file format config A whitespace or comma-separated list None of class names for initialization. n META-INF/MANIFEST.MF contains JAR metadata java.util.logging. The default handler level Level.ALL for n META-INF/services can contain service provider FileHandler.level FileHandler, Level.INFO for configuration java.util.logging. ConsoleHandler.level ConsoleHandler n Use the jar utility to make JAR files java.util.logging. The class name of the default filter None FileHandler.formatter java.util.logging. jar Utility Options ConsoleHandler.formatter Option Description java.util.logging. The class name of the default formatter java.util.logging. FileHandler.formatter XMLFormatter for c Creates a new or empty archive and adds files to it. If any of the specified file java.util.logging. FileHandler, names are directories, the jar program processes them recursively. ConsoleHandler.formatter java.util.logging. C Temporarily changes the directory. For example, SimpleFormatter for ConsoleHandler jar cvfC myprog.jar classes *.class changes to the classes subdirectory to add class files. java.util.logging. The default encoding default platform FileHandler.encoding encoding e Creates a Main-Class entry in the manifest java.util.logging. jar cvfe myprog.jar com.mycom.mypkg.MainClass files ConsoleHandler.encoding f Specifies the JAR file name as the second command-line argument. If this java.util.logging. The default limit for rotating log files, 0 (No limit), but set parameter is missing, jar will write the result to standard output (when creating a FileHandler.limit in bytes to 50000 in jre/lib/ JAR file) or read it from standard input (when extracting or tabulating a JAR file). logging.properties i Creates an index file (for speeding up lookups in a large archive) java.util.logging. The default number of rotated log files 1 FileHandler.count m Adds a manifest to the JAR file. java.util.logging. The default naming pattern for log files. %h/java%u.log jar cvfm myprog.jar mymanifest.mf files FileHandler.pattern The following tokens are replaced when the file is created: M Does not create a manifest file for the entries. Token Description t Displays the table of contents. / Path separator jar tvf myprog.jar %t System temporary directory u Updates an existing JAR file %h Value of user.home system property jar uf myprog.jar com/mycom/mypkg/SomeClass.class %g The generation number of rotated logs v Generates verbose output. %u A unique number for resolving naming conflicts x Extracts files. If you supply one or more file names, only those files are %% The % character extracted. Otherwise, all files are extracted. jar xf myprog.jar java.util.logging. The default append mode for file loggers; false FileHandler.append true to append to an existing log file O Stores without ZIP compression DZone, Inc. | www.dzone.com
  • 6. 6 Core Java tech facts at your fingertips COmmON javac OpTIONS COmmON java OpTIONS Option Purpose Option Purpose -cp or -classpath Sets the class path, used to search for class files. The class path is a -cp or -classpath Sets the class path, used to search for class files. See the previous list of directories, JAR files, or expressions of the form directory/'*' table for details. Note that javac can succeed when java fails if the (Unix) or directory* (Windows). The latter refers to all JAR files current directory is on the source path but not the class path. 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 -ea or Enable assertions. By default, assertions are disabled. directory. If a class path is specified, the current directory is not -enableassertions automatically included—add a . item if you want to include it. -Dproperty=value Sets a system property that can be retrieved by System. -sourcepath 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 getProperty(String) source path is specified, it is set to the current directory. -jar Runs a program contained in a JAR file whose manifest has a -d Sets the path used to place the class files. Use this option to separate Main-Class entry. When this option is used, the class path is ignored. .java and .class files. -verbose Shows the classes that are loaded. This option may be useful to -source Sets the source level. Valid values are 1.3, 1.4, 1.5, 1.6, 5, 6 debug class loading problems. -deprecation Gives detail information about the use of deprecated features -Xmssize Sets the initial or maximum heap size. The size is a value in bytes. -Xlint:unchecked Gives detail information about unchecked type conversion warnings -Xmxsize Add a suffix k or m for kilobytes or megabytes, for example, -Xmx10m AbOUT ThE AUThOR RECOmmENDED bOOKS Cay S. Horstmann Core Java, now in Cay S. Horstmann has written many books on C++, Java and object- its 8th edition, is a oriented development, is the series editor for Core Books at Prentice-Hall and a frequent speaker at computer industry conferences. For four years, no-nonsense tutorial Cay was VP and CTO of an Internet startup that went from 3 people in a and reliable reference tiny office to a public company. He is now a computer science professor into all aspects of at San Jose State University. He was elected Java Champion in 2005. Java SE 6. Publications n Core Java, with Gary Cornell (Sun Microsystems Press 1996–2007) n Core JavaServer Faces, with David Geary (Sun Microsystems Press 2004–2006) n Big Java (John Wiley & Sons 2001–2007) bUy NOw Web Site Blog books.dzone.com/books/corejava1 http://horstmann.com http://weblogs.java.net/blog/cayhorstmann books.dzone.com/books/corejava2 Get More FREE Refcardz. Visit refcardz.com now! Available: Core Seam Essential Ruby Core CSS: Part I Core CSS: Part III Essential MySQL Struts2 JUnit and EasyMock Core .NET Hibernate Search Getting Started with MyEclipse Very First Steps in Flex FREE Equinox Spring Annotations C# Core Java Groovy EMF Core CSS: Part II NetBeans IDE 6.1 Java Editor XML PHP RSS and Atom JSP Expression Language Getting Started with JPA GlassFish Application Server ALM Best Practices JavaServer Faces Silverlight 2 Design Patterns Published June 2008 HTML and XHTML Visit refcardz.com for a complete listing of available Refcardz. 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 4 million pages each month to 919.678.0300 more than 1.7 million software developers, architects and decision Refcardz Feedback Welcome makers. DZone offers something for everyone, including news, refcardz@dzone.com $7.95 tutorials, cheatsheets, blogs, 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.