Sunteți pe pagina 1din 6

class: package declaration always 1st line, import between pkg and class, non-access modifiers allowed for

class : strictfp, final, abstract; class: public or default; default access: Think of default access as package-level access, because a class with default access can be seen only by classes within the same package. package cert; class Beverage { } ----package exam.stuff; import cert.Beverage; class Tea extends Beverage { } -- not compile, must be in the same package or public strictfp applies only for classes -------interface default: public abstract; volatile not permitted in interface, no static methods, abstract allowed (not necessary)

All variables defined in an interface must be public, static, doStuff(String...x) (... in between only!) and FINAL (even implicitly) method cannot be final, static, private neither protected constructor - cannot be final, static, abstract byte< short(2)< int(4)< long(8)<< float <double Type Bits Bytes Minimum Range Maximum Range byte 1 -2^7 2^7-1 (128) short 2 -2^15 21^15-1 (- 32768) int 4 -2^31 2^31-1 long 8 -2^63 2^63-1 float 4 n/a n/a double 8 n/a n/a volatile, transient - only instance variables instance variables (inside class) gets default value; local variables (inside method) must be initialized Thread[] threads; // Recommended Thread threads []; // Legal but less readable String[][][][][] occupantName; String[] managerName [][][]; no numbers(array size) on the left size !!! enums inside class but not in methods, cannot be private/protected; semicolon optional when no further declarations polymorphism: overriden methods are picked according to impl on runtime ONLY for instance methods (not static, not variables) Overload MUST change arg list in the constructor u can call static methods/vars (super(getRandom())) constructors: Boolean Byte Character Double Float Integer Long Short boolean or String byte or String char double or String float, double, or String int or String long or String short or String

subclass cannot decrease visibility of methods, members(i.e. public->protected) if super sth() throws Exception and child.sth() does not, Super s = new Child(); s.sth() also throws it! return type in overriding method may be subclass of return type of superclass' method watch: static meethods cannot access insstance vars (main)

widening >> boxing class AddBoxing { static void go(Integer x) { } static void go(long x) { } public static void main(String [] args) { int i = 5; go(i); // calls long version!! }} Boxing >> varargs class BoxOrVararg { static void go(Byte x, Byte y){} static void go(byte... x) { } public static void main(String [] args) { byte b = 5; go(b,b); // Byte, Byte }}

Widening >> varargs class AddVarargs { static void go(int x, int y) { }static void go(byte... x) {} public static void main(String[] args) { byte b = 5; go(b,b); // calls int, int } int x = 7; switch (x) { case 2: System.out.println("2"); default: System.out.println("default"); case 3: System.out.println("3"); case 4: .... /// output: default 3 4

1 / 6 mgorski.net

for( ; ; ) { System.out.println("Inside an endless loop"); } for (int i = 0 , j = 0; (i<10) && (j<10); i++, j++) { System.out.println("i is " + i + " j is " +j); // ok } int b = 3; for (int a = 1; b != 1; System.out.println("after loop")) { b = b a; }

int i = 0; for (;i<10;) { i++; // like do-while } for (int i = 0 , long j = 0; .... /// NOT allowed

outer: for (int i=0; i<5; i++) { for (int j=0; j<5; j++) { System.out.println("Hello"); continue outer; } // end of inner loop System.out.println("outer"); // Never enters here }

try { } catch (IOException e) { } catch (FileNotFoundException ex) { // unreachable catch block !! will not compile }

ArrayIndexOutOfBoundsException ClassCastException IllegalArgumentException IllegalStateException NullPointerException NumberFormatException AssertionError ExceptionInInitializerError StackOverflowError NoClassDefFoundError
asserts java -ea -da:com.geeksanonymous...

private void doStuff() { assert (y > x): "y is " + y + " x is " + x; // ( boolean result ), anything that returns object } "1231312".length(); System.out.println(new int[]{1}); StringBuilder StringBuffer (java5+), thread safe DateFormat and NumberFormat objects can have their locales set only at the time of instantiation

String x = "0123456789"; System.out.println( x.substring(5) ); // output is "56789" System.out.println( x.substring(5, 8)); // output is "567" StringBuilder sb = new StringBuilder("0123456789"); System.out.println(sb.delete(4,6)); // output is "01236789"

tokenizer - look for period: String[] tokens = s.split("\\.");

printf: "-" Left justify this argument "+" Include a sign (+ or -) with this argument "0" Pad this argument with zeroes "," Use locale-specific grouping separators (i.e., the comma in 123,456) "(" Enclose negative numbers in parentheses System.out.printf(">%2$b + %1$5d< \n", i1, false);

public boolean equals(Object obj), hashCode(), and toString() are public

interfaces Collection Set SortedSet List Map SortedMap 2 / 6 mgorski.net

maps: HashMap Hashtable TreeMap LinkedHashMap comparable:

Queue NavigableSet NavigableMap sets: HashSet LinkedHashSet TreeSet PriorityQueue equals() MUST take Object int compareTo() Generics, -1 when this < comparable

class DVDInfo implements Comparable<DVDInfo> { public int compareTo(DVDInfo d) { return title.compareTo(d.getTitle()); lists: ArrayList Vector LinkedList

Comparator: class GenreSort implements Comparator<MyClass> public int compare(<MyClass one, <MyClass two) { return one.getGenre().compareTo(two.getGenre()); } list.toArray() Arrays.asList(sa); poll() - removes, priority queue give last one peek() - does not remove offer() - adds

binarySearch MUST be predicted by sort(, the same comparator) returns -1 when different comparator Iterators: terator<T> it = d.iterator(); while (it.hasNext()) { T tt = it.next(); // no cast

3 / 6 mgorski.net

legacy mode cannot unbox objects

Thread: public static void sleep(long millis) throws InterruptedException InterruptedException is declared exc

4 / 6 mgorski.net

wait(), notify(), and notifyAll() must be called from within a synchronized context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.

public static void yield() public final void join() throws InterruptedException public final void setPriority(int newPriority) Object: public final void wait() throws InterruptedException public final void notify() public final void notifyAll() enum constructor: only private or default!

wait() trhows java.lang.IllegalMonitorStateException when not in synchronized context

public static <E extends Number> List<E> process(List<E> queue: remove() - returns E nums){ collection<E> remove(E e) retunrs boolean return nums; } treeset - class needs to implement comparable Predefined character classes . Any character (may or may not match line terminators) \d A digit: [0-9] \D A non-digit: [^0-9] \s A whitespace character: [ \t\n\x0B\f\r] \S A non-whitespace character: [^\s] \w A word character: [a-zA-Z_0-9] \W A non-word character: [^\w] ^ The beginning of a line $ The end of a line \b A word boundary \B A non-word boundary \A The beginning of the input \G The end of the previous match \Z The end of the input but for the final terminator, if any \z The end of the input Greedy quantifiers X? X, once or not at all X* X, zero or more times X+ X, one or more times X{n} X, exactly n times X{n,} X, at least n times X{n,m} X, at least n but not more than m times \Q Nothing, but quotes all characters until \E \E Nothing, but ends quoting started by \Q

todos: sorting + deriviation IdentityHashMap finally - not guaranteed to complete? check: PriorityQueue<String> pq = new PriorityQueue<String>(); pq.add("2"); pq.add("4"); System.out.print(pq.peek() + " "); pq.offer("1"); pq.add("3"); pq.remove("1"); System.out.print(pq.poll() + " "); if (pq.remove("2")) System.out.print(pq.poll() + " "); System.out.println(pq.poll() + " " + pq.peek()); which modifiers allowed for inner class (in method class)

console.readPassword() returns char array - variable names (allowe charactes - # disallowed) - cohesion (jedno, spjno) -ohesive means that a certain class performs a set of closely related actions. A lack of cohesion, on the other hand, means that a class is performing several unrelated tasks. - A extends B, B o = new A(); o.method (calls A) o.instanceVar (calls B!!!). only isntance methods - in loop cannot redeclate variable - call(7) will be casted/boxed to integer - int[][] cannot be casted to int[] - isntance of checks real object A a = new B(); instance of checks B - IllegalArgumentException is superclass ofNumberFormatException - for (int j=0, n=0,w=0 ; j<10; j++){ System.out.println("+"+j+n+w); } // correct, but only one keyword - for(int i=0;i<3;++i) { System.out.print(i + ".."); } // priints 0,1,2 - to call wait(), the thread must own the lock on the object that wait() is being invoked on - synchronized === synchronized on (this) how scanner works (java.util)

5 / 6 mgorski.net

6 / 6 mgorski.net

S-ar putea să vă placă și