java oca resume

16
Class: template discribing state & behavior of objects of this type Object: @Runtime + new make object of class = instance of class own state & access State: own unique set of instance variables of object Behavior: methods Identifiers: names for Java components. Some legal rules & conventions. Keywords: not used as identifiers Inheritance: reusage in other classes. Ie. superclasses & subclasses. Interfaces: 100% abstract superclass which methods to support, but not how Cohesive: every class focuesd set of responsibilities Packages: organizing the classes use import to add them Legal identifiers: rules of compiler whether name is legal o Unicode characters o Start letter, $ (currency), connecting char (ie _ ) NO DIGIT! o After letters, currency, connecting, numbers o No limit o No Java keyword: abstr act assert (1.4) boole an break byte case catch char class const contin ue default do double else enum (1.5) extend s final final ly float for goto if implement s impor t instance of int interfa ce long native new package priva te protect ed public return short static stric tfp super switch synchroni zed this throw throw s transie nt try void volat while

Upload: raf

Post on 13-Sep-2015

13 views

Category:

Documents


3 download

DESCRIPTION

Resume of the book OCA/OCP Java SE 7 Programmer I & II Study Guide..

TRANSCRIPT

Class: template discribing state & behavior of objects of this type Object: @Runtime + new make object of class = instance of class own state & access State: own unique set of instance variables of object Behavior: methods

Identifiers: names for Java components. Some legal rules & conventions. Keywords: not used as identifiers

Inheritance: reusage in other classes. Ie. superclasses & subclasses. Interfaces: 100% abstract superclass which methods to support, but not how Cohesive: every class focuesd set of responsibilities Packages: organizing the classes use import to add them

Legal identifiers: rules of compiler whether name is legal Unicode characters Start letter, $ (currency), connecting char (ie _ ) NO DIGIT! After letters, currency, connecting, numbers No limit No Java keyword:abstractassert (1.4)booleanbreakbytecase

catchcharclassconstcontinuedefault

dodoubleelseenum (1.5)extendsfinal

finallyfloatforgotoifimplements

importinstanceofintinterfacelongnative

newpackageprivateprotectedpublicreturn

shortstaticstrictfpsuperswitchsynchronized

thisthrowthrowstransienttryvoid

volatilewhile

Case-sensitivity Oracles Java Code Conventions: recommendations naming classes, variables, methods Classes&Interfaces: CamelCase; nouns & adjectives Methods: lowerCamelCase; verb-noun pairs Variables: lowerCamelCase Constants (static&final): UPPER_CASE

Source file declaration rules: Only 1 public class per source code file Comments independent of any rule Public class must match filename (Eg public class Example Example.java) If part of package package first line before import If import between package & class declaration Import & package apply to all classes in source code file File can have more than 1 nonpublic class File with no public class any name not matching classes in file Compiling with javac: javac [options] [source files] Launching with java: java [options] class [arg] public static void main(String[] args) Of String x Of String args[] Fully qualified name package + class name Import FQN OR * to get more than 1 class Import static if a class contains static members, object references, constants

Access modifiers !!!--> altijd kijken of code compileert!!!!acces controls: public protected private no modifier = default/package Nonaccess modifiers strictfp final abstract

Class access: creating instance, extending, accessing certain methods & variables visibility public all classes from all packages access to public class, but import needed @ different package! no modifier package only Class nonaccess: final no subclassing/extending abstract no instantiation if 1 abstract method whole class abstract. Nonabstract methods are possible!

Interface: what, not how All methods public & abstract! -> NOT static All variables public, static, final constants Implemented by classes Can extend other (multiple) interfaces NOT implement public abstract interface == public interface public abstract void method() == void method() anything else wont compile! public static final var=var

Class method access modifiers: public, protected, private public all classes accessible protected by inheritance (subclass) even if in different package (but not by instance.var!!!) OR if in same package default in same package only private no access outside class No (access) modifiers @ local variables, except final Nonacces method modifiers: final, static, abstract, synchronized, strictfp, native final prevents overriden final argument cannot be modified abstract declared, not implemented! must be implemented by extended non-abstract class (not by extended abstract class) Never together with final or private!!!! @ top-level not with static.. synchronized only 1 thread at a time native implemented in platform-dependent code (C) no implementation strictfp forcing floating points (IEEE 754)OCP

variable argument lists arguments between () parentheses @ invocation of method parameters methods signature var-arg type specify the type of the argument(s) basic syntax var-arg int nameArray [type+ellipsis+space+name] other arguments can be used as well

constructor declarations no return type same name as class no static, abstract or final! variable declarations: final, public, protected, private, static, transient, volatile primitives char (16 bit Unicode), boolean, byte, short, int, long, double, float small to big integer: byte (8 bit) short (16 bit) int (32 bit) long (64 bit) & float (32 bit) double (64 bit) signed negative (1) / positive (0) = first bit @ left reference specific type; can be used to refer to subtype of declared type instance inside class, outside method 4 access levels final or transient NOT abstract, synchronized, strictfp, native instance != static shadowing: declare a local variable with same name as instance variable array declarations always object on the heap declare, construct, initialize IE int name [] / int[] name ; int[][] name / int[] name [] No size of array in declaration!!! final variables primitive: 1 time initialisation object: 1 time referencing transient variables skip variable @ serialization volatile variables (thread must reconcile own private copy) static variables & methods, innerclasses, init blocks independent of instances

enums enum Name { VAR1,VAR2,VAR3 } outside class public or default modifier constructors -> is instantiated when instantiating 1 enum, instance variables, methods, constant specific class body -> overriding method of specific enum MyEnum.values() array of MyEnums values

Instance variable private Accessor & mutators (get & set) methods public get & set Every class subclass of Object Inheritance by extending classes Promote code reuse Polymorphism IS-A extends class & implements interface Sub & super HAS-A class has a reference to another class Reference = variable one type & once declared never type change Reference type defines methods that can be invoked Reference variable can refer to any object of same type as declared ref & to any subtype Reference variable declaration as class / interface type Extend ONLY ONE If overridden compiler knows this Only reference is important to know methods; not instance Rules: Equal argument list Same return type / subtype Access modifier not more restrictive Access modifier CAN be less restrictive Instance methods only overriden if inherited by subclass (not private, final) Overriding method CAN throw unchecked execption regardless overriden method declares exception Overriding method MUST NOT throw checked execptions that are new or broader than declared by overriden method But can however throw narrower OR fewer exceptions Keep in mind that compiler will still throw error of overriden method if the reference is of this same superclass Cannot override final method Cannot override static method If method cannot be inherited, it cannot be overriden super.methodOverridenName() will invoke the overriden method

Overloading reuse same method name; different arguments MUST change argument list CAN change return type CAN change access modifier CAN declare new / broader checked exception Overloaded in same OR sub class If object overloading reference type (not instance!) determines which method!!!

Downcasting only when instanceof is of subtype Upcasting it restricts number of methods you can invoke

interface implementation must have implementation of each method of interface no checked exceptions other than declared by interface maintain signature & return type of interface method if abstract class implementing interface no method implementation needed! class can implement more than 1 interface interface can extend (more than 1!) other interface(s) legal return types overloading = name reuse you cannot only change return type! must change argument list overriding return type must be subtype of declared return type (in 1.5) if primitive return type any value that can implicitly be converted (thus for example char to int), or explicitly cast declared returning object can be of subtype constructors & instantiation Every class INCLUDING abstract, MUST HAVE constructor Constructor has no return type & match class name Typically used to init instance variables new object constructor invoked at runtime constructors can by any access modifier (incl private only class itself can instantiate object of that type so class must provide static method / variable that allows access to instance creation within the class) method can have same name as class but doesnt make it a constructor if no constructor default constructor always no-arg if arg constructor must make a no-arg if needed every constructor has first statement overload constructor (this()) or superclass constructor (super())!!! default constructor automatic super() super() can include args cannot access instance method/instance variable before super constructor only static variables & methods can be accessed by super or this abstract classes have constructors always called when concrete subclass is instantiated interfaces no constructors constructor can only be invoked within another constructor if superclass only has constructor with args & subclass no constructor compiler error default constructor invokes super() which does not exist! Constructors are never inherited! if using this(method()) method needs to be static, because no instance can be invoked until after the super constructor has run some constructor will always make the call to super()! if two constructors both calling eachother StackOverflowError

initialization blocks { x = 8; } static class is first loaded instance instance is created after call to super()!!! order matters! static variables & methods they belong to class, not instance main is static can only get static variables nonstatic cannot access static & static cannot access nonstatic static variable/method Classname.method() or Classname.variable, but you can also use an object reference (thus ref.variable or method()) in constructors you can declare static & nonstatic variables! static methods cannot be overriden!!! (they can be redefined however) reference needs to be subclass; it will not automatically use method of subclass

primitive literal: source code representation of primitive data type Integer: decimal, octal, hexadecimal, binary 1000000 = 1_000_000 underscore used to clarify number (cannot use it at beginning or end or next to decimal point) Binary literal: 0B101010 or 0b0001 prefix 0b Octal: 0-7 07, 010 (=9) prefix 0 Hexadecimal: 0-9 & a-f (16 symbols not case sensitive) prefix 0x 0xfff, 0xabcdef0123 Long: same as integer with L/l suffix (bv 0xabcL) Floating-point: number decimal - number Double: 8.8 Float: 8.8F less precise No a comma but a dot!!! Boolean true / false character c; \u004E; prefix \u number literal from 0-65535 is legal! (so binary, octal, hexadecimal all legal) else needs cast escape by \ Assignment Reference way to get to object primitive literal integer = int byte b = 27 compiler casts like byte b = (byte) 27; int or smaller expressions always int, thus: byte a=3; byte b=8; byte c = a+b; compiler error needs cast!!! Primitive casting implicit widening conversion explicit narrowing could lose info

From long -> double = ok; from double -> int without cast not! Example: byte b = (byte) 130L; -126 no error! float assigment MUST have cast (float) OR f behind the value!!! If literal value (thus numeric value) is to high to assign compiler error 128 to byte 10000000 is negative flip = 01111111 add 1 10000000 = -128 += etc lets you add value without a cast! (implicit) Reference variable assignment assignment can be a subclass scope variable scope from longest scope to shortest: static, instance, local, block, init, constructor { int x=3; } only in brackets init block! shadowing overlapping two scopes when out of scope compiler error initialization instance variables are initialized to default value Object=null, byte,short,int,long=0, float,double=0.0, boolean=false,char=\u0000 NullPointerException with object initalized to null! Array instance all array elements have default values, always! local variables must ALWAYS be initialized before usage! else compiler error if a conditional block with init compiler complains it might not have been initialized object null is not the same as unitialized! local = not null as default Object references are copied, except for String (=immutable) passing variables into methods Object you pass copy of reference Not pass-by-reference for objects pass-by-value (variable-value) pass-by-copy-of-the-variable Cant change callers ariable; but called method can change object the variable is referencing to. You cannot reassign a callers reference to a different object in the called method: thus not Foo f=new Foo(); doStuff(f); doStuff(Foo g){ g = new Foo(); } f is now referencing different object of g! For primitives: pass-by-copy-of-the-bits-in-the-variable Garbage collection / objects lifecycle Heap where objects live only 1 heap JVM decides to run garbage collector Each thread has own execution stack each own lifecycle; can be alive or dead (non-String) object is eligible for garbage collection when no live thread can access it Java can run out of memory Methods to remove a object: Remove reference by referring to null Reassign a reference variable Isolating a reference reference in reference if first reference not reached (=null) then removed finalize() run code before object is deleted by collector method inherited by Object for any object, finalize will be called once(!) by garbage collector calling finalize can save object from deletion

assignment operators size matters @ primitives reference variable is no object type matters at value compound assignment opterators: +=, -=, *=, /= relational operators: =, ==, != equality: numbers, characters, boolean primitives, object reference .equals for String case sensitive! instanceOf check if object reference variable is of particular type. A null reference can also be tested always false of course. Compiler error @ two different class hierarchies!!! (if no relation) +, -, *, / % modulus remainder of a division When + sign with numbesr & String from left to right if first numbers then numbers add + concate String. If first String then all Strings concatenated. increment/decrement operators: ++, -- if prefix, done before expression, if postfix after this final variables cannot be changed! compiler error conditional operator: x = (bool expression) ? value to assign if true : value to assign if false; logical operators: &, |, ^, !, &&, || short-circuit (does not waste/perform pointless evaluations): &&, || non-circuit: &, | ^ exclusive-OR (XOR) ONE expression needs to be true (not both)! ! boolean-invert opposite of booleans current value (bitwise operators: &, |, ^)

String = Immutable Object! Each character 16-bit Unicode character Each declaration/editing new object creation! When using String method (e.g. concat, toUpperCase, replace), but not referenced not changed String class final not overridable String s = ; one String object & ref var; String s = new String() two objects, one ref var charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), trim() StringBuilder not thread safe compared to StringBuffer Is a mutable object! Capacity: new StringBuilder() 16 chars capacity; new StringBuilder(ab)16+arg length; new StringBuilder(int) int-value Append, insert updates capacity automatically Insert after index of StringBuilders length exception append(value) update value with argument (String, boolean, char, double, float, int, long) delete(int start, int end) start is zero-based; end is one-based insert(int offset, String s) offset is zero-based reverse() toString() Arrays: declaring: int[] key; int key[]; int[][] keys; int[] keys[]; NO SIZE OF THE ARRAY IN THE DECLARATION (NOT int[5] key)!!! constructing: creating array object on the heap how much space size: = new int[4]; multidimensional: int[][] keys = new int[3][]; keys[0]=new int[5]; . initializing object references not assigned are null! with length you can loop through the array to init the elements in one line: int[] dots = {6,7,8}; multidimensional: int[][] keys = {{1,2,3},{4,5},{6,7}} anonymous array: int[] key; key = new int[] {2,3,4}; arrays can only have one declared type! for primitives if smaller bit its ok; for superclass subclass references ok if changing reference primitives has to be same type!!! (not as above); for subclasses its ok The Collection API: Lists, Sets, Maps, Queues List l = new ArrayList(); polymorphic declaration java.util.List & java.util.ArrayList You can override Objects toString method for listing through list! add(el), add(index, el), clear(), contains(el), get(index), indexOf(el), remove(index), remove(el), size()

if(boolean expression){ } else { } optional else if(boolean expression) { } zonder {} alleen eerstvolgende regel geldt! switch(expression: char, byte, short, int, enum, String){ case outcome: { } use break! default: { } does not have to come at the end! outcome value MUST BE compile time constant!!! outcome value must meet expression type requirements (thus byte type cannot take 128) no duplicate outcome value String: case-sensitive equality while loop while(bool expression){ } do { } while(bool expression); basic for for(declaration & initialization; boolean expression; iteration expression){ } you can declare more of same type (!) by using commas (,)! break, return, System.exit() & exception cause loop termination for( ; ; ;) legal!!! Some can be blank & for example bool exp filled advanced for for (type varName : list/array) { } break stop loop continue stop current iteration labeled loops: exampleName: for() {} used to define which loop to break / continue break exampleName;

try{ } catch(Exception){ } finally{ } always executed at some point after the try block try{ } finally { } legal! Exception propagation: the exception if not caught thrown to bottom of call stack if @ main() halt JVM Exception instance of class (subclass) of java.lang.Exception Exception derived from Throwable ( Object). Error is also derived from throwable (for example memory problems) can all been thrown printStackTrace() catch if has subclasses caught as well Exception handling at catch blocks goes from top to bottom so put sub-exceptions first! else compile error exception already caught Declare throwable exceptions in method; void method() throws ,{ } not for RuntimeExceptions! (=unchecked) & Error Handle or declare: throw or try-catch Creating own exception: class MyException extends Exception{ } catch(IOException e){ throw e; } also good but if checked also declare it! JVM Exceptions thrown by JVM ArrayIndexOutOfBoundsException: out of length of array ClassCastException: cast reference fails IS-A test NullPointerException: declared but not instantiated (value=null) StackOverflowError: recursion too deeply ExceptionInInitializerError: initialize static variable in initializing block NoClassDefFoundError: cant find class, because command-line error, classpath issue, missing class file Programmatic Exceptions thrown by application / API programmers NumberFormatException: cannot convert String to number AssertionError (not exception): assert boolean test return false IllegalArgumentException: argument differently formatted as expected one IllegalStateException: when state of environment doesnt match operation