-
-
-
Inheritance: variables are not overridden. Map: no add(…) method, only put(…). Cannot call super or this from inside a static context. Watch out for out of scope variables. Is-a relationship relays on inheritance and polymorphism. The final modifier assures that a reference variable cannot be referred to a different object, but final does not keep the object’s state from changing. Initialization blocks run when the class is first loaded (a static initialization block), or when an instance is created (an instance initialization block). Furthermore, instance init blocks run RIGHT AFTER the constructor’s call to super(). List cares about index. ArrayList gives us fast iteration and fast random access. Vector is the same as an ArrayList but its methods are synchronized. LinkedList gives fast insertion and deletion. Set cares about uniqueness. HashSet is an unordered, unsorted Set. LinkedHashSet is an ordered version of HashSet. Use the former instead of the latter when you care about the iteration order. TreeSet is a sorted collection, where elements will be in ascending order, according to natural order (or specific order by using Comparable or Comparator), and which implements the SortedSet interface. Map cares about unique identifiers. HashMap is an unordered, unsorted Map. Good for adding and removing elements. It allows one null key and multiple null values. Hashtable is like HashMap but its methods are synchronized. No null keys or values are allowed. LinkedHashMap maintains insertion order, and gives you faster iteration. TreeMap is a sorted (natural order) Map that implements the SortedMap interface. Case expressions (from switch statements) must be constant expressions. Watch for the order in which methods are called within threads. Protected is less restrictive than default. Overriding method can be final. The first expression in an assert must always result in a boolean value, while the second expression in an assert statement can be anything that results in a value (void returning methods cannot be used in an assert statement). Using Java 5, if assert is an identifier, then “javac –source 1.3 …” will compile with warnings, while “javac –source 1.4/1.5/5 …” will not compile; if assert is a keyword, “javac –source 1.3 …” will not compile, while “javac –source 1.4/1.5/5 …” will all compile. Using Assertions Appropriately: do NOT use assertions to validate arguments to a public method; do NOT use assertions to validate command-line arguments; do NOT use assert expressions that can cause side effects; DO use assertions to validate arguments to a private method; DO use assertions, even in public methods, to check for cases that you know are never supposed to happen. If a method does not handle an exception (does not have a catch block), the finally block is executed before the exception is propagated. To access a method from a class located outside the package of the accessing class, those methods need to be public. Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore (_). An expression involving anything int-sized or smaller is always an int. +=, -+, *=, and /= all put in an implicit cast (i.e. “byteB += 1” works while “byteB = byteB + 7” will not because the result is an int). When you pass an object variable into a method, you actually pass a copy of the reference variable (copy of the bits representing the reference to an object). We have System.gc() and Runtime.getRuntime().gc(). Comparable interface requires an “int compareTo(T o)” method; the Comparator interface requires an “int compare(T o1, T o2)” method. 1
-
method of the Enum class returns the position of the constant in its enum declaration. It IS legal to switch on an enum. IllegalArgumentException, IllegalStateException, NumberFormatException, and AssertionError are thrown programmatically. The classpath is set with the –cp or –classpath option when using java. When used with the javac command, -classpath is NOT looking for the source file, but rather for whatever classes the source file needs. When used with the java command, -classpath needs to specify where the source class file is + all class files used by the source file. All of the wrapper classes except Character provide two constructors: one that takes a primitive of the type being constructed, and one that takes a String representation. Wrapper conversion methods: xxxValue() – converts a Wrapper to a primitive; parseXxx(String) – converts a String to a primitive; valueOf(String) – converts a String to a Wrapper. When you see the primitive in the method, than a primitive is returned. Overloading when we have method matching: widening beats boxing and var-args, while boxing beats var-args. You CANNOT widen from one wrapper type to another (IS-A fails). You CANNOT widen and then box, but you CAN box and then widen. An (non-String) object can be (garbage) collected even if it has a valid reference, if no live thread has access to the object. For any given object, finalize() will be called at most once by the GC. With regex, \d searches for digits, \s for whitespace character, \w for a word character (letters, digits, or “_”), \D searches for non-digit characters, \S for non-whitespace characters, and \W for non-word characters. The default case in a switch statement works just like any other case for fall-through (no break). The && and || are short-circuiting logical operators (if from evaluating the left-hand expression it can determine the result, the right-hand expression will not be evaluated). & and | evaluate ALL expressions involved. The handlers for the most specific exceptions must always be placed above those for more general exceptions. If you throw an (checked) exception from inside a method, you must either surround that statement with a try-catch block, or add throws declaration to the method. If you are a serializable class, but your superclass is NOT serializable, then any instance variables you INHERIT from that superclass will be reset to the values they were given during the original construction of the object. This is because the non-serializable class constructor WILL run. transient and static fields are not serializable. In hashing retrieval, first you have to find the right bucket (using hashCode()), second you have to search the bucket for the right element (using equals()). The equals() – hashCode() bound (IF Condition – THEN Required): ordinal()
Condition (IF) Required (THEN) x.equals(y) == true x.hashCode() == y.hashCode() x.hashCode() != y.hashCode() x.equals(y) == false -
When searching an array or collection (using binarySearch()), they have to be sorted. If the collection is not sorted, the results are undefined. If the collection/array you want to search was sorted using a Comparator, it MUST be searched using the same Comparator, which is passed as the second argument to the binarySearch() method. Comparators cannot be used when searching an array of primitives. 2
-
-
When using the Comparator interface, you will typically create a separate class for every different sort sequence you want to implement. Wildcard syntax allows a generic method to accept subtypes (or supertypes) of the declared type of the method argument (void addD(List f) {} – can only take ; void addD(List extends Food>) {} – can take a or ). The collection can ONLY be accessed, NOT modified. You CANNOT use the wildcard notation in the object creation (i.e. “List> foo = new ArrayList extends Animal>() ”). Explicit cast from a subclass to a superclass IS allowed (although the compiler does it automatically). Overloading methods can have different access levels than the overloaded method. If an enum constant is declared with an argument, an enum constructor that takes the type of the argument MUST be supplied. extends ClassA> or super ClassA> means any type that IS of type ClassA or a sub/supertype of ClassA. An Interface can be marked public, default, and/or abstract, and a (non-inner) class can also be final. super.super…. is not allowed. For sorted collections, the elements need to be of the same type (mutually comparable), i.e. you cannot have both Integers and Short or Long in a TreeSet (Long and Integer objects are not comparable). Polymorphism applies only to instance methods, not to static methods, and not either to static or instance variables. System.out.println(1 + 2 + “” + 4 + 5) will print 345. When used in a comparison, a Wrapper object is unboxed first! NumberFormat and DateFormat classes are abstract, not concrete classes. Locale is a final class. To import static members, an import statement must begin with import static, and include, either with a wildcard or explicitly, the static members to be imported. When using static imports, you either use directly the static member, or use the full class path. When using static imports, the class itself is not imported, only the static members of the class. So to use the class itself, you need to write another import, or to specify the full class name (including package name) when you use it. When using the equals method, the two objects do not necessary need to be of the same type, in which case the method will return false (i.e. using equals between a String and StringBuffer, even though they might store the same value, will return false). A method can throw the same or fewer, but not more, exceptions than the superclass method it is overriding. %b will print true for any non-boolean variable, and false if the argument provided is null. If “enum E {N, E, S, W}; E e = E.E;” then “e equals E.E” and “e == E.E” are true. Method toArray() returns Object[] so cast might be needed, while toArray(T[] a) returns T[], so no cast is needed. Runtime polymorphism takes places for overridden methods. Overloaded methods are determined at compile time and are based on the reference type. You cannot assign a char to a short or vice versa without an explicit cast. Unless it is overridden, the equals() method behavior in Object, and therefore inherited from it, performs the same reference comparison as the == operator. Boolean and String classes override this method. StringBuffer does NOT override this method. The overriding method must return the same type (or a type that is a subclass of the return type of the overridden method) as the method in the superclass. You can implement an interface even if a superclass of yours already implemented it. In a method with a primitive return type, we CAN return any value or variable that can be implicitly converted to the declared return type. 3
-
-
Any cast exception is thrown at RUNTIME when not using generics. If you use wait(), notify() or notifyAll() methods from within a non-synchronized context, you will get a RUNTIME exception, not a compilation error. Inner classes can use public, private, default, and protected modifiers. Having “double[] d = {1, 2, 3};”, d is an instance of double[] and an instance of Object. Cannot convert from a Wrapper type to another (i.e. from a Short to an Integer, or from a Long to an Integer, or from a short to an Integer). toLowerCase(), toUpperCase(), replace will return a reference to the original string object if it is already in lower case or upper case or there is nothing to replace, which means that == operator will return true. Having public void method1(Integer… I) and public void method1(int… i) in the same class will not compile, because the compiler will treat both methods to be the same. The same goes for int[] and int… (none if them is more specific – see following note). If parameters in method A are valid in Method B, but NOT vice versa, then Method A is more specific than Method B. This is important for the compiler when it tries to determine which method to call (will always choose the more specific one). When NOT using generics, you can add to a collection different types of Objects, which will give a type safety warning at compile time but execute successfully. If one would use generics, a compile time error would be thrown. The following options can be used while creating and extracting a JAR file:
The order of evaluation of an expression is from left to right (i.e. x = x * --x; will print 90, not 81 when x is 10). System.out.printf(“%f”, 100); will compile successfully but throw an IllegalFormatConversionException at runtime because 100 is an integer, not a float. System.out. printf(“%f”, 100.12); will compile and execute successfully. If one of the operands for division is a double value, that when dividing by zero, you get the value Infinity instead of an ArithmeticException at runtime. You can NOT have char[] ch; ch = {…};
-
in two different statements. The two lines above must appear in the same statement. toString() method has been overridden for the following collections: ArrayList, Vector, EnumSet, HashSet, TreeSet. It prints the list of elements enclosed in square brackets. Characters take the null character as the default value. Before an addition operation is performed on two characters, both of those two characters are first promoted to integer type, and only then, the addition takes place between those two integer values. You cannot use the instanceof operator to test across two different class hierarchies. You cannot override a static method with a non-static one, and vice versa.
4
-
~i = (- i) – 1, where i is an integer type variable. If an enum declares an abstract method, then all the enum constants
-
method. Enums can NEVER extend any other enum or class. abstract methods cannot be private; they can only be public or protected. Arrays.toString(…) returns a String, not an array of Strings. method1(Object… obj1) and method2(Object[] obj2) are the same, so compilation fails. byte b = x does not need a cast if -128 <= x <= 127. The String class does NOT have an append or reverse method, while StringBuffer has.
5
have to implement that abstract
-
Re-throwing an exception (without catching it) from the finally block of a try-catch statement means that the next statement after finally block will never be executed. Natural ordering of Strings from low to high: space, numbers, all uppercase letters, underscore, all lowercase letters. Watch out for length vs. length(). When two classes inherit from the same base class, those classes are called sibling classes. You cannot assign an object reference to a sibling reference, even with casting. Enumerated values are public static final, so they can be statically imported.
-
Pattern p = Pattern.compile(“[12345]”); Matcher m = p.matcher(“a1b2c3d4e5f6”); while(m.find()) System.out.println(m.start() + “ ” + m.group());
-
public FileWriter(String filename, boolean append) throws IOException.
-
The combination of the “abstract” and “synchronized” modifiers is NOT allowed. FilenameFilter is an interface that defines the accept() method that accepts or rejects specified filenames. The compiler will fail to compile code that defines an overriding finalize() method that does not explicitly call the overridden finalize() method from the superclass. Java permits local variables and instance variables to have the same name. Java uses local variables if there is a local variable and an instance variable with the same name. String and Wrapper classes are immutable. Casting an object to an interface type that was implemented by the class is OK. In i < 20 ? out1() : out2(), out1 and out2 cannot have void as the return type. a = 1; a = a++; a will be 1. a = 1; a += a; a will be 2. From the JSL: 1 Evaluate Left-Hand Operand First 2 Evaluate Operands before Operation 3 Evaluation Respects Parentheses and Precedence 4 Argument Lists are Evaluated Left-to-Right For Arrays: First, the dimension expressions are evaluated, left-to-right. If any of the expression evaluations completes abruptly, the expressions to the right of it are not evaluated. Example: The statement arr[i] = i = 10; will be processed as follows:
-
arr[i] = i = 10; ==> arr[0] = i = 10 ; ==> arr[0] = 10 ; java -ea: myPackage.myProgram java -da:<package>... myPackage.myProgram
==>
i = 10; arr[0] = i ;
To enable assertion for one package and disable for other you can use: java -ea:<package1>... -da:<package2>... myPackage.myProgram
-
In order for the static blocks and static members of a class to be initialized, the class must be actively used. (Class1 c = null; is not enough; should be Class1 c = new Class1();) An automatic variable is actually a local variable. If an inner class is defined in an instance method of the encapsulating class, then a non-final local variable of that instance method is not accessible from the inner class. In a subclass, access members of the superclass by means of inheritance, and NOT through objects of the type of the superclass. The following code works: long LL = 7; if (LL == 7.0) {…}
6
-
Inner classes cannot have the same name as their enclosing classes. The instanceof operator returns true for the class of the x reference and all of the parent classes. If objects are of different types, the equals test fails:
-
Integer nA = new Integer( 4096 ) ; Long nB = new Long( 4096 ) ; nA.equals(nB) will return false. The += operator has been overloaded for the String and Wrapper classes. The -= has not been overloaded for the String class. The toString() method called on a String object will return the object itself, not a new object.
-
Interfaces can be declared private or protected if they are members of class definitions. Member interfaces can only be defined inside a top-level class or interface. Cannot reference a field before it is defined (forward referencing not allowed). If a method declared in an interface does not through any checked exceptions, then the implementing method from a concrete class should also not through any checked exceptions. If the interface method throws any exception, the implementing method does not need to through them. Careful about unreachable catch block for different exceptions if you never throw it from the try statement body. Exceptions for this rule are the public classes Throwable, Error, Exception, and RuntimeException. Format string conversion: For %b(boolean) : All data types For %c(char) : byte, char, short, int For %d(int) : byte, short, int, long For %f(float) : float, double For %s(string) : anything
-
Watch out for methods that are overloaded instead of overridden. In this case, the object itself does not matter if it is of a sub-type (subclass) class or not. Enum elements are of different classes. For example: enum Gender {MALE{}, FEMALE{}} Gender.MALE.getClass() will print class MainClass$Gender$1 Gender.FEMALE.getClass() will print class MainClass$Gender$2
-
Top-level private classes are not allowed (only public, default, abstract and/or final). null instanceof AnyClass will return false. StringBuffer sb = “abcd”; gives a compilation error because you need to use the new operator to construct a StringBuffer. In case of inheritance, an explicit cast is needed if we go done the class hierarchy. No explicit cast is needed if we go up the class hierarchy. Be careful at the following scenario: class A {} class B extends A {} … A a = new A(); B b = new B(); b = (B)a; //THIS LINE WILL THROW A ClassCastException at runtime!
-
All Wrapper classes are final, so they cannot be sub-classed. List > list and List extends Object> are the same. 7
-
When using System.out.format(…), if a width is used as part of the first parameter of the format method, then that width specifies a minimum no. of digits allowed, NOT a maximum. It is ok to serialize an object if its un-serializable instance variable has not been instantiated. Watch out for unreachable code (line 6 below will never be reached, BUT line 10 will !!!):
try { 4. System.out.print("before "); 5. throw new MyException(); 6. System.out.print("after "); 7. } catch (MyException fe) { 8. System.out.print("catch "); 9. } 10. System.out.println("done ");
-
-
Watch out for the use of assert as a keyword in a source file, but when running the code, assertions are not enabled! Methods with ‘no body’ have to be declared as abstract if part of a (abstract) class. An enum may NOT be declared in a method. With Wrapper classes, you can call the equals method on a Wrapper giving it a primitive as a parameter (Autoboxing makes all this possible): int x1 = 10; Integer x2 = x1; x2.equals(x1); //Calling equals on x1 on the other hand will give you a compilation error In an abstract class, an abstract method cannot be marked private. The abstract and strictfp modifiers cannot be applied to variables. The getTime() method of the Date class returns a long, while the getTime() method of the Calendar class returns a Date object. When using the split method of the String class, the end of the input String creates one more
terminator. -
method takes a type T as an argument, so any primitive array will not work if the reference is also parameterized. final instance variables have to be initialized either at the point of declaration, or inside a constructor. Whether assertions are turned on or off is a Runtime concept. Your assert statements are compiled never the less. The javac command does not support the -da or -ea flags. For the following code: Arrays.asList
final int i; i = 127; byte b = i;
since the variable i is not instantiated in the same line where it is declared, you will get a compiler error if you do not explicitly cast the i variable to byte. If you would have had: final int i = 127; byte b = i;
-
then everything would have worked just fine. In the following code: List extends Number> type = new ArrayList(); // 1 for ( Integer n : type ) {…}
8
type has to be Number, not Integer!
-
Cannot use static and this in the same expression (i.e. static Class1 iClass1 = this;) When using Collections.sort(list), the elements in the list must all implement the Comparable interface and must be mutually comparable. If they do not, you will get a ClassCastException at runtime. When using a sorted collection (like TreeSet), all its elements must implement the Comparable interface. You could pass a Comparator object to the constructor of the sorted collection. If they do not, you will get a ClassCastException at runtime. Final objects are not allowed in a case statement. A final object's value can be changed whereas a final variables value cannot be changed. The method Arrays.sort cannot take an array of boolean values as its input. static protected variables defined in a super class outside of the subclass’ package can be accessed because they are static. If they were not static, then they could not be accessed. A package statement must come before any import statements. The modifiers abstract and final cannot be used together. A method cannot be marked abstract and provide an implementation. A top-level class cannot be marked private, but only public or left without an access modifier (for default "package" access). It is an error to use the same modifier twice on a class. strictfp can be applied only to classes or to methods, not to variables. Watch out for more than one top-level class marked as public. The compareTo method cannot compare two different types of enum variables. The format() and printf() methods are similar to the printf method in the C language. When using polymorphism, the method called on the actual object MUST be defined in the reference class also. Map does not extend the Collection interface. A class with a private constructor cannot be inherited. A field cannot be declared as being both final and volatile. In generic methods, the type parameter must be declared before the return type of the method, but after the modifiers (i.e. public static <X, Y extends X> boolean isPresent(X x, Y[] y){}). In the Queue class, the remove() and poll() methods remove and return the head element of the queue. They differ only in their behavior when the queue is empty, namely the remove() method throws an exception, while the poll() method returns null. From within the same class, creating an instance of that class and accessing a private member, IS LEGAL. The finalize() method of the Object class is protected. If two classes do not share an inheritance relationship, trying to do an explicit cast from one to another will cause a compilation error. Assigning an incompatible type to a reference variable will cause a compilation error. In regular expressions, having “(?i)” for example will cause the case of “i” to be ignored. The list() method of the File class returns an array of Strings, while the listFiles() method an array of Files. For an object to be deserialized properly, the first superclass in its inheritance hierarchy that does not implement Serializable must have a no-arg constructor. Violating this rule will cause the readObject() method to throw an InvalidClassException at runtime. The following code will not compile: Vector v = new Vector(); 9
v.add(10); for (int i : v) {…} -
because the declared type of v is Vector not Vector. There is no Thread constructor that takes an int as one of its arguments. The join() method of the Thread class is overloaded to take a long (and long, int) as its argument. Integer[] cannot be applied to a method that has int…i as its argument. The && and || operators work only with boolean operands. Garbage collection is performed by a low priority daemon thread. To find the size of a File, you use the length() method. If you use i.e. “\s” instead of “\\s”, the compiler will complain because it does not recognize the former as being a legal escape sequence. Arrays are serializable only if all their elements are serializable. The Vector class does not have a sort() method. You can add duplicates to a (generic) Vector, and you can add null to it. If x is a primitive variable, then synchronized(x) will fail to compile (no Autoboxing). final instance variables have to be explicitly initialized by the time the constructor has completed. If you call super.finalize() in your class, remember that in the Object class, the method throws a Throwable, so you have to handle it. Any exceptions thrown by the finalize method are ignored by the garbage collector. If you pass null to a method call, than all method definitions (that take as an argument an Object of some type) match the method call. In such cases, the compiler attempts to choose the most specific method. When using Collections.sort on a collection that has String elements, that collection will be sorted in ascending order of ASCII codes, which means that strings starting with capital letter will come before those starting with a lower case letter. Integer, Double, Float and Long provide the toHexString() method. If a method takes a primitive as its argument, and you override it and provide a Wrapper as its argument, it will work just fine due to Autoboxing. A local class is defined within a body of a method. Within a local class, you cannot use a local variable defined inside another local method than the one in which this local class was defined. A nested class is a static inner class. The call method(10) is considered ambiguous by the compiler when having two methods, method(int… x), and method(float… x). If the main method is not correctly defined, you will get a runtime exception, not a compilation error. int x, y = 10; means that x is not initialized, only y is. If you call the next() method on a Scanner object, but there are no tokens (namely hasNext() would return false), you will get a RuntimeException. The months field of the Calendar starts from 0. Static members and static blocks are initialized in the order in which they appear in the class definition. Instance initializers and member initializers are executed in the order in which they appear in the class. Static code blocks run before initialization blocks. Trying to compare an enum with a String using == operator, will cause a compilation error (incomparable type error).
10
-
Read through the API docs for classes like String, StringBuffer, Wrapper classes, I/O classes (like File, FileReader, PrintWriter, etc), Date, Calendar, Date- and NumberFormat, Locale, Thread, Object, etc.
11