Java Cheat Sheet

Reviews
Shared by: armani11
Stats
views:
136
rating:
not rated
reviews:
0
posted:
11/9/2008
language:
pages:
0
Java Cheat Sheet Comments // C++ comments that extend from the double slash until the end of the line /* Between C like comment delimiters */ /** * Comments used by JavaDoc to automatically generate documentation. * First line is a summary. Can imbed HTML code. Some key tags include: * @param parameterName description * @return description * @throws ExceptionClassName description of circumstances * @see class, class#method, #constructor, #method, or #field */ Keywords abstract boolean break byte case catch char class continue default do double else extends final finally float for if implements import instanceof int interface long native new package private protected public return short static super switch synchronized this throw throws transient try void declares that a class or method is abstract declares a boolean variable or return type exit from a loop declare a byte variable or return type one case in a switch statement handle an exception declares a character variable or return type signals the beginning of a class definition prematurely return to the beginning of a loop default action for a switch statement begins a do while loop declare a double variable or return type signal the code to be executed if an if statement is not true specify the class which this class is a subclass of declare that a class may not be subclassed or that a field or method may not be overridden code guaranteed to be executed after a try block declare a floating point variable or return type begin a for loop execute statements if the condition is true declare that this class implements the given interface permit access to a class or group of classes in a package test whether an object is an instance of a class declare an integer variable or return type signal the beginning of an interface definition declare a long integer variable or return type declare that a method is implemented in native code instantiate a new object define the package in which this source code file belongs declare a method or member variable to be private declare a class, method or member variable to be protected declare a class, method or member variable to be public return a value from a method declare a short integer variable or return type declare that a field or a method belongs to a class rather than an object a reference to the parent of the current object test for the truth of various possible cases Indicate that a section of code is not thread-safe a reference to the current object throw an exception declare the exceptions thrown by a method This field should not be serialized attempt an operation that may throw an exception declare that a method does not return a value 1 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info volatile while Warn the compiler that a variable changes asynchronously begin a while loop Primitive data types Note: the primitive types are defined regardless of platform or operating system Type char byte short int long float Signed? unsigned Unicode signed signed signed signed signed exponent and mantissa signed exponent and mantissa Bits Bytes 1 16 8 16 32 64 32 1 2 1 2 4 4 Lowest false '\u0000' -128 -32,768 -2,147,483,648 ±1.40129846432481707e-45 Highest true '\uffff' +127 +32,767 +2,147,483,647 ±3.40282346638528860e+38 boolean n/a 8 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807 double 64 8 ±4.94065645841246544e-324 ±1.79769313486231570e+308 Examples of variables: float f; int i, j, k; char c = 'A'; // float variable declared // three integer variables declared // char variable declared and initialised Referenced data types In addition to the primitive data types, Java supports three kinds of referenced data types: interfaces, classes and arrays. Variables for referenced data types Whereas primitive variables contain the value of the primitive, reference variables do not hold an object. A reference variable holds only a reference to an object or null. Note: (1) A variable of class X may refer to an instance of class X. (2) A variable of class X may also refer to an instance of any of X’s subclasses. (3) A variable of class Object may refer to an instance of any class. (4) A variable of interface Y may refer to an instance of any class that implements the Y interface; however, this variable only allows access to the methods and variables declared in the Y interface. (5) variables for referenced data types can also contain null (no reference), see NullPointerException below. Be aware: (1) Object assignment (eg. a = b;) does not copy the object, only the reference the object. (2) The boolean equality test (o1 == o2) does not compare the contents of two object variables, only the object references (3) Declaring a reference variable as final does not protect the contents of the referred object from being changed (if allowed by the object definition). Class // Class definition – an example of the canonical form public class Name extends Object implements Comparable, Cloneable, Serializable { // Note: class Name {…} is shorthand for class Name extends Object {…} 2 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info // constants – always static and final – access as appropriate private static final int MAGIC_NUMBER = 19680502; // class member variables – almost always private or protected private double x; private double y; // class constructors – Note: must not call final methods // Java provides a default noargs constructor if you do not provide one // - but if you provide a constructor, Java will not provide the default public Name() { this.x = 0; this.y = 0; } // a noargs constructor public Name(double x, double y) { this.x = x; this.y = y; } // Note: call super( … ) if the parent constructor requires the variables. // Consider: having a trivial constructor and a complex init() method. // accessor methods public double getX() { return x; } public double getY() { return y; } // mutator or modifier methods public void setX(double x) { this.x = x; } // void methods have public void setY(double y) { this.y = y; } // no return values // Note: there are good reasons to prefer immutable classes // Important: override the default toString() method (from Object) // - because it is used by the Java input/output system public String toString() { return "[" + x + "," + y + "]"; } // Note: override the default equals() method (from Object) // Note: Must be symmetric - if a.equals(o) then o.equals(a) as well. // Note: the parameter must be an Object (otherwise it overloads equals()) public boolean equals(Object that) { if (this == that) return true; // identity - a.equals(a); if (that == null) return false; if (this.getClass() != that.getClass()) return false; // return false if any individual fields in this and that differ if(this.x != that.x) return false; if(this.y != that.y) return false; return true; } // Note: override the default hashCode() method (from Object) public int hashCode() { // implement consistent with equals() // two equal objects have the same hashCode() result return …; } // // // // } Class variables: declaration and instance creation // Assume that a class Point {…} has been defined: Point p; // At this point p refers to null p = new Point (3, 4); // Now p refers to an instance: Point q = new Point (4, 5); // declaration and creation combined // Note: variable declaration does not create an instance of a class 3 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Note: if implementing the interfaces: . Cloneable override clone() . Comparable override compareTo() - used with TreeMaps . Serializable override readObject() and writeObject() //other methods and inner classes as needed for class functionality Note on copy constructors: Copy constructors are important in C++ because the assignment operator will copy an instance using the provided copy constructor. In Java, assignment only copies a reference to an instance. But, even when explicitly called in Java, C++ styled copy constructors do not work as expected. If object copying is needed, implement Cloneable and override clone(). Note on destructors: Overriding the finalize() method is not the same as the C++ destructor: finalize() is called by the garbage collector and should be used for releasing limited "resources" (such as open files). There is no guarantee the finalizer will be called. Therefore it is not generally used for other purposes. If needed, write a terminate() method, & check the boolean terminated variable. Class inheritance: Inheritance maps related classes into each other in a hierarchical way. Java has a single rooted class hierarchy without multiple inheritance; however, aspects of multiple inheritance can be simulated using Java's interface abstraction. All classes inherit (extend) directly or indirectly from Object. Inheritance overuse warning: Generally inheritance should only be used when the subclass has an is-a and a works-like-a relationship with the superclass it specialises. In other circumstances, because inheritance weakens encapsulation and often results in fragile code, composition (using a variable of another class) should be favoured over inheritance (extending another class). As a general rule, classes should be declared as final unless you are designing them to be used for inheritance. Access: For methods and variables, there are four levels of access: private, protected, public, and (in the absence of a access modifier) package-private. Classes can be public, otherwise they are package-private. Final: final classes cannot be subclassed. final methods cannot be overridden in a subclass. Final variables are constants that cannot be changed after initialisation. Final method arguments will not be changed by the method. Static: static methods and variables are not instanced for every new object created – all instances share the one copy of the method or variable. Abstract: abstract classes and methods are not fully implemented. Abstract methods are designed to be overridden in subclasses. Abstract methods can only exist inside abstract classes and interfaces. Abstract classes cannot be instantiated. Interface An interface is the highest level of abstraction which allows dynamic method resolution at run time. An interface is like a class with nothing but abstract methods and final, static fields. All methods and fields of an interface must be public. Interfaces cannot be instantiated. Interfaces are most useful for defining types. Variables can be defined in terms of an interface as well as a class. // Interface example - canonical form public interface NameOfInterface extends anotherInterface, andAnotherInterface { //all member variables declared are implicitly public, final, and static String myString = "My String"; //all methods are implicitly abstract and public //method implementations are not permitted!! void setFactor(Object factor); Object getFactor(); } 4 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Note: A class can implement many interfaces, but inherit from only one class. Note: the keywords transient, volatile, and synchronized, and the access specifiers private and protected CANNOT be used in declaring Interface members. String The String type is a special class object that is recognised by the java compiler. All text between double quotes is a String. So we can type: String s1 = "this is more efficient"; String s2 = new String( "than this!" ); Note: Strings are implemented in Unicode and not ASCII. Note: The String class is immutable (read only) and final (cannot be extended). Note: (s1 == s2) compares the references. Use s1.equals(s2) to compare Strings. Note: Strings can be concatenated using the + sign: String s3 = “big “ + “deal”; Note: The java compiler implements concatenation using the StringBuffer class. Note: Avoid a lot of String concatenation by using StringBuffer and toString(). Wrapper classes for the primitive data types Because the primitive data types do not extend the Object class, they can not be used as arguments to methods that demand an object. To get around this restriction there is a wrapper class for each primitive. Primitive data type boolean char byte short int long float double Corresponding wrapper class Boolean Character Byte Short Integer Long Float Double Array // array variable declaration String[] names; // names is initialised with the null reference int[][] m; // m is initialised with the null reference // array creation - Note: declaring an array names = new String[50]; // an array of m = new int[4][5] // a 4x5 array int[] k = new int[10]; // declaration does not create it! 50 Strings of integers and creation steps combined // array initialisation int[] k = {1, 2, 3}; double[][] identityMatrix = { {1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {0.0, 0.0, 1.0} }; Note: all array indexes are integers from zero through to N-1. In run time, array bound checking is always done. An ArrayIndexOutOfBoundsException is thrown when an array index is used that is less than zero or greater than or equal to the array size. 5 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Note: Array variables are references. The assignment operator (=) does not actually copy an array! However, the static System.arraycopy() method can be used to copy arrays. Note: Java has some useful array methods including: binary search; fill; and sort that are available by importing the class library java.util.Arrays. Information about an array (such as its length) can be found using methods from the java.lang.reflect.Array class library. Naming conventions Type Class Convention Noun or Noun phrase. First letter of each word capitalised. All lower case. Domain names reversed. Example ArrayList, Particle, Inventory, Catalogue info.ozpolitics.utility Package Interface Method Adjective. First letter Runnable, Serializable of each word capitalised Verb or verb phrase. First word lowercase. Additional words capitalised. First word lowercase. Additional words capitalised. save, restore, getKey, calculateResults, insert Variable i, j, gridReference Constant (static final) All uppercase. All words MAX_BUFFER_SIZE, separated by underscores MIN_WIDTH Program // the minimal program: HelloWorld.java public class HelloWorld { // Note: the ClassName is case sensitive and the same as FileName.java // Note: the compiled program will be in the file FileName.class public static void main (String[] args) { // every program has a public static void main! // program code goes here! System.out.println("Hello world\n"); } } Operator precedence Precedence 1 postfix ops 2 unary ops 3 create/cast 4 multiplicative 5 additive Operator [] . (params) expr++ expr-++expr --expr +expr -expr ~ ! new (type)expr * / % + Association Left Right Right Left Left 6 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Precedence 6 shift 7 relational 8 equality 9 bitwise AND 10 bitwise XOR 11 bitwise OR 12 logical AND 13 logical OR 14 conditional 15 assignment Operator << >> >>> < > <= >= == != & ^ | && || ? : = *= /= += -= <<= >>= >>>= = ^= |= Association Left Left Left Left Left Left Left Left Right Right Program control Note: Java program control syntax is much the same as C and C++ Note: Blocks contained between curly brackets. But single statement blocks after if, else, for, while, and do, do not need the curly brackets. If/else if (a > b) System.out.println(a); else System.out.println(b); Switch switch (n) { case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; default: System.out.println("something else"); } While while (!finished()) playItAgainSam(); Do do { getNextItem(); if (bypassThisOne()) continue; processThisItem(); if (seenEnough()) break; } while (moreData()); For for(;;) // forever – can also use while(true) { doSomething(x++, y--); if (x > y) break; } for (int i = 0 ,j = n; i 0 : "algorithm expects x to be greater than zero" false : "This statement should never be reached"; x == y; // Note: this example does not have a message Use exceptions to tell you if something has gone wrong. Exceptions are used to deal with known problems. Use assert statements often to verify and document known facts. They are designed to be cheap and they help fight programming bugs. Note: Because their execution can be turned off at runtime, use Exceptions (and not assertions) to test the validity of arguments to public methods. Also, only use exceptions to deal with potential input/output errors . 9 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Note: Because their execution can be turned off at runtime, assertions should not be used to (implicitly) calculate values. (BAD: assert x++>y;) As assert statements are new in Java 1.4, they must be compiled explicitly: javac –source 1.4 JavaFile.java At runtime, the –ea flag (for enable asserts) is used to indicate that the asserts should be tested. java –ea JavaFile Collections and maps Available by importing java.util.* Implementations Resizable Array Balanced Tree TreeSet ArrayList TreeMap Set Interfaces List Map Hash Table HashSet HashMap Linked List LinkedList HashSet: A set backed by a hash table TreeSet: A balanced binary tree implementation of the SortedSet interface Function: Sets do not allow duplicates. HashSet is much faster than TreeSet, but offers no ordering guarantees. Hierarchy: HashSet and TreeSet are subclasses of Set, which is a subclass of Collection. Some Set Methods: int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator(); Set s = new HashSet(17); // allocate a HashSet with initial capacity of 17 ArrayList: A resizable-array implementation of the List interface LinkedList: A doubly-linked List Function: Lists have a sequence and can be accessed by integer index position. For most purposes ArrayList is faster and more appropriate. Hierarchy: ArrayList and LinkedList are subclasses of List, which is a subclass of Collection. Some List Methods: int size(); boolean isEmpty(); Object get(int index); Object set(int index, Object element); void add(int index, Object element); Object remove(int index); Search: int indexOf(Object o); int lastIndexOf(Object o); Iteration: ListIterator listIterator(); ListIterator listIterator(int index); Utilities: Imported from java.util.Collections - sort(List); shuffle(List); reverse(List); fill(List, Object); copy(List dest, List src); binarySearch(List, Object); HashMap: A hash table implementation of the Map interface TreeMap: A balanced binary tree implementation of the SortedMap interface Function: A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value. The situation for Map is exactly analogous to Set. HashMap is much faster than SortedMap but offers no ordering guarantees. Hierarchy: HashMap and TreeMap are subclasses of Map. Map is not a subclass of Collection. Some Map Methods: Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); Boolean containsValue(Object value); int size(); boolean isEmpty(); The synchronization wrappers add thread-safety to an arbitrary collection. There is one static factory method for each of the six core collection interfaces: 10 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info synchronizedCollection, synchronizedSet, synchronizedList, synchronizedMap, synchronizedSortedSet, and synchronizedSortedMap. Two examples follow: List list = Collections.synchronizedList(new ArrayList()); Collection c = Collections.synchronizedCollection(myCollection); synchronized(c) { Iterator i = c.iterator(); // Must be in synchronized block! while (i.hasNext()) foo(i.next()); } The unmodifiable wrappers take away the ability to modify the collection, by intercepting all of the operations that would modify the collection, and throwing an UnsupportedOperationException. Like the synchronization wrappers, there is one static factory method for each of the six core collection interfaces: unmodifiableCollection, unmodifiableSet, unmodifiableList, unmodifiableMap, unmodifiableSortedSet, and unmodifiableSortedMap. Input/Output File system The File class represents the pathname (a String) to some file or directory. File creation and deletion are handled through the File class. Useful methods include exists(), canRead(), canWrite(), isDirectory(), createNewFile(), etc. Byte based streams Streams are the primary metaphor for Java's input/output system. Streams can be read from or written to. InputStream is the base class for byte-based input with many useful subclasses such as FileInputStream FileInputStream fos = new FileInputStream("filename"); // Key methods include read(), read(byte[]), and void close() OutputStream is the base class for byte-base output with many useful subclasses FileOutputStream fos = new FileOutputStream("filename"); // Key methods include write(int), write(byte[]), flush() and void close() Buffering - use BufferedInputStream and BufferedOutputStream BufferedInputStream bis = new BufferedInputStream(fis); (Unicode) character streams Reader is the base class for Unicode character input FileReader fr = new FileReader(filename); // Key subclass: FileReader: Writer is the base class for Unicode character output Key subclass: FileWriter FileWriter fw = new FileReader(filename); // Key subclass: FileReader: Buffering - use BufferedReader and BufferedWriter BufferedReader br = new BufferedReader(new FileReader(filename)); InputStreamReader and OutputStreamWriter act as bridges between byte based streams and reading and writing Unicode character streams. Reader r = new InputStreamReader(anInputStream); 11 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Data streams DataInputStream and DataOutputStream are important subclasses of InputStream and OutputStream. They have useful methods for reading and writing binary formats for the primitive data types to and from files. Buffering: use BufferedInputStream and BufferedOutputStream. DataInputStream dis = new DataInputStream( new BufferedInputStream( new FileInputStream("filename"); The standard input/output streams System.in - The standard input stream // read a byte from standard input Byte b = System.in.read(); // read a line from standard input BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = in.readLine(); System.out - The standard output stream System.out.println("Message"); System.err - The standard error output stream Random Access File Random access files do not use the stream metaphor! Rather the file can be thought of as a large array. It can be opened in read-only mode ("r"), read-write mode ("rw"), rw-mode with synchronous writes of content ("rwd"), and rw-mode with synchronous writes of content and metadata ("rws"). RandomAccessFile raf = new RandomAccessFile("name", "rw"); This class has many useful methods including readType() and writeType() where Type is a particular primitive type such as like readByte(), seek(), setLength(), close(), etc. Note: The RandomAccessFile class is not buffered and can generate many calls to the underlying operating system. The NIO FileChannel metaphor is a more efficient (but much more complicated) method for accessing random access files. Some design patterns Singleton A class with a one-instance only guarantee. Typically used to represent intrinsically unique components - such as hardware resources. Two general implementations both based on a private constructor and access via a public static member. public class Singleton1 { public static final Singleton1 INSTANCE = new Singleton1(); private Singleton1() { … } } // private constructor guarantees singelton // other methods to provide functionality. 12 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info public class Singleton2 { private static final Singleton1 INSTANCE = new Singleton2(); private Singleton2() { … } // private constructor guarantees singelton public static Singleton2 getInstance() { return INSTANCE; } // other methods to provide functionality. } Type safe enumeration // stand alone public final class FruitEnum { private final String name; private FruitEnum(String name) public String toString() public static final FruitEnum APPLE public static final FruitEnum ORANGE public static final FruitEnum BANANA } // inside another class public final class DataBase { public static class OpenMode { public static final OpenMode public static final OpenMode public static final OpenMode public static final OpenMode public String toString() private OpenMode(String om) private final String openMode; } public DataBase(String, filename, OpenMode mode) { // etc. } // the rest of the database implementation } { this.name = name; } { return name; } = new FruitEnum(“apple”); = new FruitEnum(“orange”); = new FruitEnum(“banana”); READER WRITER CREATE NEW_DB = = = = new new new new OpenMode("Reader"); OpenMode("Writer"); OpenMode("Create"); OpenMode("New database"); { return openMode; } { this.openMode = om; } 13 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info Incomplete below here Threads AWT Predefined colours: (eg. Color.black) black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow. Swing Containers Top level: JApplet, JFrame, JDialog. General purpose: JPanel, JScrollPane, JSplitPane, JTabbedPane, JToolBar. Special purpose: JInternalFrame, JLayeredPane, JRootPane. Controls Buttons: JButton, JMenuItem, JToggleButton, Applets Applets are written by extending the java.applet.Applet class and overriding key methods from the super classes. Typically an applet will override one or more of init(), start(), stop(), paint(Graphics), update(Graphics), and/or destroy(). Unlike applications, applets do not need implement a main method. Every applet is implemented by creating a public subclass of Applet, which the browser calls. The inheritance hierarchy of the Applet class determines much of what an applet can do and how: Object  Component  Container  Panel  Applet  MyApplet. import java.applet.Applet; import java.awt.* public class MyApplet extends Applet { // After the constructor is called, the browser calls init() to perform // basic initialisation of the applet. public void init ( ) { … } // Once the init() method is completed, the browser calls start() // Also called when a user brings their attention (back) to an applet public void start ( ) { … } // stop()is called when the applet becomes invisible. This happens // typically when the browser is minimised or it follows a link to a URL. public void stop ( ) { … } // The Graphics object gives direct control over the screen public void paint (Graphics g) { … } // update(g) in the super class is often overridden because it is called // by the browser to clear the screen and then repaint the Graphics g. // This results in grey flickering. public void update (Graphics g) { paint(g); } // Called before the applet is unloaded completely public void destroy ( ) { … } } // end ClassName 14 Version: 9 November 2008 from www.ozpolitics.info/java. Comments and suggestions for improvement can be emailed to bryan@ozpolitics.info

Related docs
Java Cheat Sheet
Views: 44  |  Downloads: 3
Java Cheat Sheet
Views: 46  |  Downloads: 10
Java Cheat Sheet
Views: 50  |  Downloads: 3
Java Cheat Sheet
Views: 3  |  Downloads: 0
Java Cheat Sheet- Abbreviated Version
Views: 13  |  Downloads: 6
Basic Java Cheat Sheet
Views: 341  |  Downloads: 16
HP JAVA Cheat Sheet
Views: 17  |  Downloads: 4
Java Graphics Cheat Sheet
Views: 235  |  Downloads: 17
JAVA SYNTAX CHEAT SHEET
Views: 0  |  Downloads: 0
HP JAVA Cheat Sheet
Views: 1  |  Downloads: 0
Erichs Java cheat sheet for C++ programmers
Views: 28  |  Downloads: 0
Cheat Sheet
Views: 2  |  Downloads: 0
premium docs
Other docs by armani11
understanding_and_managing
Views: 406  |  Downloads: 1
Audit Release and Settlement
Views: 249  |  Downloads: 4
Personal Financial Statement
Views: 1045  |  Downloads: 40
Chart of Federal Businesses Tax Filings
Views: 433  |  Downloads: 7
Board Resolution Authorizing New Borrowing
Views: 182  |  Downloads: 3
Customer Bounced Check Letter
Views: 4291  |  Downloads: 47
Stock Certificate for Common Stocks
Views: 459  |  Downloads: 17
edens_1b-all
Views: 160  |  Downloads: 1
Sales Tax Exemption Certificate 6378 State Of Cal
Views: 1030  |  Downloads: 5
Initial Notification of COBRA Rights
Views: 391  |  Downloads: 5