Beruflich Dokumente
Kultur Dokumente
1
- ordinal() 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):
- 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<Food> f) {} – can only take <Food>; void addD(List<?
extends Food>) {} – can take a <Food> or <Rice>). 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/super-
type 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>
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 have to implement that abstract
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
- 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());
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.
- 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.
- Arrays.asList 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:
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:
- 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:
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