a cupful of Java! Web Hosting by Netfirms | Free Domain Names by Netfirms SUN CERTIFIED JAVAPROGRAMMER FOR JAVA2 PLATFORM 1.4 Table of Contents Basics of Java programming Language fundamentals Operators and assignments Declarations and Access Control Control flow,exception handling and assertions Object-orientedprogramming Nested classes and Interfaces Object lifetime Threads Fundamental Classes Collections and Maps Thiswork is primarily intended to be a guideline for those taking the SunCertified Programmer for the Java 2 Platform 1.4 examination. Itis recommended that the candidate check Sun's website for any changesin the pattern of the exam.Copyright© 2005 Rohit George.Permissionis granted to copy, distribute and/or modify this documentunderthe terms of the GNU Free Documentation License, Version 1.2orany later version published by the Free Software Foundation;withno Invariant Sections, no Front-Cover Texts, and no Back-CoverTexts. A copy of the license is included in the section entitled“GNUFreeDocumentation License”.Basics of Javaprogramming Objects are manipulated through objectreferences (and aliases). newoperator returns a reference to a new instance of the classinstantiated. Objects have their copy of instance members,while static members belong only to the class. Local (or Automatic)variables are created inside methods/ blocks. Static members may be accessed by the class nameas well as the object references, but Instance variables can only beaccessed by the object reference. Two fundamental mechanisms of building newclasses from existing ones : Inheritance (IS-A relationship) Aggregation (HAS-A relationship) Java supports aggregation where only the referencesto objects and values of primitive data typesare stored within the aggregation class. Java 2 SDK enforces that at the mostonly one class in the source file has publicaccessibility. Each class definition in a source file is compiled intoa separate class file, containing Java byte code.There can be anynumber of classes named 'main' created in a class, provided they takeother arguments, are not publicand static, or return a value. TopLanguagefundamentals Identifier is composed of a sequence ofcharacters, where each character could be either a letter, currencysymbol, digit or connecting punctuation. However first character cantbe a digit. Examples of illegal identifiers : 48chevy,all@hands, grand-sum Keywords : abstract default implements protected throw assert do import public throws boolean double instanceof return transient break else int short try byte extends interface static void case final long strictfp volatile catch finally native super while char float new switch class for package synchronize continue if private This Reserved Literals : null true false Reserved Keywords not currently in use : const goto synchronized, abstract, strictfp and native can only be applied tomethods. transient and volatile can only be applied tovariables. static and final can be applied to both. The class containing at least one abstractmethod has to be declared as abstract. However an abstractclass need not have any abstract methods in it. Literal denotes aconstant values : Integer Literals int, long, byte, short,octal, hexadecimal Floating pointLiterals suffix f or F, dor D; exponent notation 1.2E-2 Boolean Literals true or false Character Literalssingle quotes, hexadecimal with prefix \u, \ddd where ddd is octal String Literals doublequotes Comment are of threetypes : single line // ... to end of line multiple line /* ... */ javadoc comment /** ... */ Comment start sequences areignored when occurring inside comments, hence making nesting ofcomments impossible. Primitive Data Types byte 8 bits -27 +27-1 Boolean short 16 bits -215 +215-1 Short int 32 bits -231 +231-1 Integer long 64 bits -263 +263-1 Long char 16 bits 0x0 0xffff Character float 32 bits Float double 64 bits Double boolean true or false only Boolean Default values forfields are false, '\u0000', 0L, 0, 0.0F, 0.0D and null. All static, instance variablesas well as object references are automatically initialized. Localvariables and object references need to be explicitly initializedbefore use. If a reference is setto null, then the program will compile but throw a NullPointerException at runtime. TopOperatorsand assignments All binary operators except for relational andassignment operators associate from left to right. Relational operatorsare non-associative.All unary operators (except for unary postfix increment and decrement),all assignment operators, and the ternary conditional operator operatefrom right to left. Precedence rules are usedto determine which operator to apply first if there are two operatorswith different precedence, following each other in theexpression. Associativity rules are usedto determine which operator to apply first if there are two operatorswith the same precedence, following each other in theexpression. Postfix [] . (parameters) (expr)++ (expr)-- Unary prefix ++(expr) --(expr) +(expr) -(expr) Unary prefix creation and cast new (type) Multiplicative * / % Additive + - Shift << >> >>> Relational < <= > >= instanceof Equality == != Bitwise/logical AND & Bitwise/logical XOR ^ Bitwise/logical OR | Conditional AND && Conditional OR || conditional ?: Assignment = += -= *= /= %= <<= >>=>>>= &= ^= |= Java guarantees that all operands of an operator are fullyevaluated before theoperator is applied. The only exceptions are &&, || and ?:. Also the operands of theoperators are evaluated from left to right. For example, in the case ofbinary operators, if the evaluation of the left hand operator causes anexception, then the right hand expression is not evaluated. Casting betweenprimitives and references is not permitted. Boolean values cannot becast to other data values and vice versa. null can be cast to any referencetype. All conversionsbetween byte, short to char are considered narrowing,because conversion to the unsigned char can lead to loss in information. Numeric Promotions Unary NumericPromotion : the operator is promoted to intif lesser than int. Examples : operands of +, - operand of ~ during array creation, value in [ ]indexing array elements, value in [ ]operands of <<, >>, >>> BinaryNumeric Promotion : both operands are converted to the broadest of thetwo and to int at the least. Examples : operands of *, /, %, +, -operands of <, <=, >, >=operands of ==, !=operands of &, ^, | Type Conversion can occur in the followingcontexts : Assignments involving primitive data types andreference types. Method invocation involving parameters ofprimitive data types. Arithmetic expression evaluation involvingnumeric types. String concatenation involving objects of String and other data types The assignment statement is an expressionstatement, which returns the value of the expression on the right handside. Integer values when widened to floating pointvalues may lead to loss of precision. Implicit Narrowing Primitive Conversions takeplace when all of the following are true: source is a constant expression of type byte, short, char or int.1 destination is byte, short or char type. Value of source is determined to be in the rangeof the destination. Integer division by 0 and remainder by 0 gives Arithmetic Exception. Floating point errors throw NaN and Infinity, -Infinity. (-0.0==0.0)is true (0.0/0.0) is NaNany operation involving NaNgives NaNany comparison involving NaN(except !=) gives NaNsquare root of negatives gives NaNto check if value is NaN, use isNaN(), defined in java.lang.Float and java.lang.Double. In the case of Arithmetic Compound AssignmentOperators (*=, /=, %=, +=, -=), since they have the lowestprecedence of all operators in Java, the full expression on the rightwill always be evaluated before the assignment. Also the left hand sidevariable (also in the expansion on the right side) is evaluated only once. Prefixed Increment/Decrement Operator firstperforms operation, then uses new value as result of the expression.Postfixed Increment/Decrement Operators use the current value as theresult of the expression first and then perform the operation. Increment and Decrement operators cannot beassociated, like in (++(++a))sincethe inner increment does not result in a variable for theother increment to operate on. Similarly, Relational and Equalityoperators are not associative since first operation would result in a boolean which cannot be the operandof the second. In the case of Object References, the Equalityand the Inequality operators check whether the two references denotethe same object or not. The state of the objects is not compared. Tocheck for Object Value Equality, equals()method of class Object may beused, provided the class overrides the method. Otherwise ObjectReference Equality and Object Value Equality are the same.2 Boolean Logical Operators can be applied to boolean operands to return a boolean value, or to integraloperands to perform bitwise operations. But Conditional Operators canonly be applied to booleanoperands. Adding 1 to the 1's complement of a positivebinary integer gives its negative. And vice-versa. Hence if given abinary number and its signed bit is one, to find the decimalequivalent, we need to take the 2's complement, determine the decimalvalue and then affix a negative sign to it. For the shift operator, a bit mask value of 0x1F (31,for int) or 0x3F (63,for long) is used by AND-ingwith the shift distance value to ensure that the shift distance alwaysstays in the range. (result of masking is <shiftvalue>%32 or 64). The conditional operator can be nested. It isassociative from right to left. Formal parameters are those defined in the methoddefinition. Actual parameters are those passed during the method call(which may vary from call to call). The number of Actual parameters must equal thenumber of Formal parameters. Individual Formal and Actual parameter pairs mustbe type-compatible. For parameter passing there are no implicitnarrowing conversions. If an object reference is declared as final thenit means that the reference value cannot be changed, however state ofthe object can be changed as usual. TopDeclarationsand Access Control Array Declarations char[] a;char a[]; Array Constructions a = new char[5]; Combined Declaration and Construction <element type1>[]<arrayname>=new <element type2>[<array size>];3 Combined Declaration, Construction andexplicit Initialization <element type>[]<arrayname>={<array initialize list>};4char[] a = {'b','c','d','e'}; AnonymousArray Construction new char[]{'b','c','d','e'} In the case of multidimensional arrays,you may specify the size only for the first dimension: String[][] s = new String[3][]; Accessing an incorrect index in thearray results in an ArrayIndexOutOfBoundsException. A class has two components : Static Context : contains staticmethods, static field initializers and static initializer blocks. Non-Static Context : has instancemethods, constructors, non-static field initializers and instanceinitializer blocks. The signature of a method contains only the method nameand the formal parameter list. Allinstance methods are passed an implicit reference to the currentobject, which can be referencedin the body of the instance by the keyword this, which can be used in anynon-static context.5 When a subclassobject is created, all the superclass constructors are invoked in orderstarting from the top of the hierarchy. Constructors cannotreturn a value and hence cannot specify a return type, not even void. The only actiontaken by the default constructor is to call the superclass constructor. If any explicitconstructors are defined, then implicit default constructor will not beprovided. It must be explicitly implemented. Static code cannotaccess non-static members. Also this and super are unavailable.However, the Non-Static code can refer to the static context members. Aninterface is an implicitly public, abstractclass containing implicitly static, finalvariables and abstract methods (if any). Interfaces with emptybodies are used as markers to tag classes as having a certain property.Such are also called ability interfaces.6 TopControlflow, exception handling and assertions The type of expression of a switch statementmust be non-long integral. All labels in a switch construct includingthe default label are optional.But there cannot be more than one defaultlabel. The case label values must be in range of type of switchexpression. Switch blocks may be nested and the case labelscan be redefined inside them. In the forloop header, two semicolons are mandatory. The 'crab' (;;) is commonly used to constructinfinite loops. If in the forloop, pre-increment instead of post-increment is used, it makes nodifference to the behavior of the loop. The scope of a label is the entire statementprefixed by the label. So it cant be redeclared as a label inside thestatement. A statement may have multiple labels. A declarationstatement cannot have a label. break()terminates the loop or block it is in, whereas continue() skips that particulariteration of the loop and continues with the next one. All exceptions are derived from java.lang.Throwable class and havethe methods getMessage() and printstacktrace(). RuntimeException, Error and their derivatives arecalled unchecked exceptions. All others are checked7.In particular Asserts throw unchecked AssertionError. In a try-catch-finallyconstruct, block notation is mandatory. There can be zero or more catch blocks but a maximum of one finally block. The catch and finally blocks must always appear inconjunction with the try and in that order. After catching anexception, the control continues from the class which handled theexception. If the finally blockthrows an exception, then this is propagated regardless of how the try block or any catch block were executed. Also, thenew exception overrules any previously unhandled exception. A valuereturned by a finally blockwill supersede other returnstatements. Any exceptionpropagated to a finally blockis nullified by any returnstatement in the finally block. When a subclass iscreated it can override a superclass methods, but the new throws clause can only throw a subset of the previousexceptions (including their subclasses) To compileassertions use $ javac -source 1.4programname.java and during running, enable it by either -enableassertions, or -ea flags. Disable by -disableassertions or -da. These options affect all non-systemclasses only8. For enabling or disablingsystem class assertions, use -enablesystemassertions, -esa andj -disablesystemassertion, -dsa. TopObject-orientedprogramming Private, overridden and hidden members of thesuperclass are not inherited. This abilityof a superclass reference to denote objects of its own class and itssubclasses at runtime is called polymorphism andis carried out by dynamic methodlookup. A call to a private instance method is notpolymorphic since such a call can only occur within the class and getsbound to the private methodimplementation at compile time. Overriding ofInstance Methods involve defining a method in the subclass with thesame method signature (which does not encompass final modifier for theparameters, but does include the return type of the method9).Note that the new method cannot narrow theaccessibility but can widen it10, andalso it can only specify all, none or a subset of the former'sexceptions. An instance methodin the subclass cannot override a staticmethod, a final method and a private method in the superclass. Inthe first case it will result in hiding of the static method, in the second acompile time error, and in the third it will result in the creation ofa completely separate method with identical signature. When an instancemethod is invoked on an object using a reference, it is the classof the current object denoted by the reference, not the type ofreference, that determines which method is implemented.When a field of an object is accessed using a reference, it is the typeof the reference, not the class of the current object denoted bythe reference, that determines which field will actually be accessed.(Treatment is just the same for staticmethods and variables too)11 class Vehicle {String mytype = new String(“Vehicle!”);void sayType() {System.out.println(“I am a vehicle”);}}class Car extends Vehicle {String mytype = new String(“Car!”);void sayType() {System.out.println(“I am a car”);}} We are overridding the field andthe method. This is how they behave : Vehicle i = new Vehicle;System.out.println(i.mytype); // prints- Vehicle!i.sayType(); // prints- I am a vehicle Car j = new Car;System.out.println(j.mytype); // prints- Car!j.sayType(); // prints- I am a car Vehicle k = new Car;System.out.println(k.mytype); // prints- Vehicle!k.sayType(); // prints- I am a car Constructors cannot be inherited or overridden.They can be overloaded but only in the same class. Java requires that a this() or super() call in the constructor (ifany) be the first statement in the constructor. If a superclass only defines non-defaultconstructors, then its subclasses cannot rely on implicit super() call to be inserted. Thiswill result in compile time error. A class choosing to partially implement themethods of an interface must be declared as abstract. Regardless of how many interfaces areimplemented, only a single implementation is provided for a member evenif it has multiple declarations in the various interfaces. Rules for assigning reference values (same rulesapply for passing references)A = B , where A = Destination reference, B = Source reference B is a class typeA is superclass of BA is interface type that B implements B is interface typeA is ObjectA is superinterface of B B is an array typeA is ObjectA is array type, where element type of B is assignable to element typeof A Casting of References checks that the referenceof the source is assignable to the reference of the destination. Thecompile time check determines if both the references can denote objectsof a reference type that is a common subtype of both. At runtime it isthe type of the actual object denoted by the source reference thatdetermines the outcome of the operation. Hence a ClassCastException may result. References of an interface type can denoteobjects of classes that implement this interface. TopNestedclasses and Interfaces Entity Declaration Context Accessib-ility Modifiers Enclosing Instance Direct Access to Enclosing Context Declarations in Entity Body Top-Level Class (or Interface) Package Public or default No N/A All that are valid in a class (or interface) body Static Member Class (or Interface)12 As static member of enclosing class or interface All No Static members in enclosing context All that are valid in a class (or interface) body Non-static Member Class13 As non-static member of enclosing class or interface All Yes All members in enclosing context Only non-static declarations + final static fields Local Class14 In block with non-static context None Yes All members in enclosing context + final local variables Only non-static declarations + final static fields In block with static context None No Static members in enclosing context + final local variables Only non-static declarations + final static fields Anonymous Class As expression in non-static context None Yes All members in enclosing context + final local variables Only non-static declarations + final static fields As expression in static context None No Static members in enclosing context + final local variables Only non-static declarations + final static fields class TLC {//Top Level Classstatic class SMC {} //Static Member Classinterface SMI {} //Static Member Interfaceclass NSMC {} //Non-static Member Classvoid nsm() {class NSLC {} //Non-static Local Class} static void sm() {class SLC {} //Static Local Class}SMC nsf = new SMC () {}; //Anonymous non-staticstatic SMI sf = new SMI() {}; //Anonymous Static} The expression <enclosing class name>.thisevaluates to a reference that denotes the enclosing object (ie. ofclass <enclosing classname>) of currentinstance of non-static member class. In the Anonymous class, SMC is not the name ofthe Anonymous class but the name of the class that you are extending orthe interface you are implementing. TopObject lifetime The lifetime of an object is time between whenit is created and garbage collected. Accessibility time of an object is time betweenwhen it is created and becomes unreachable. Resurrection after garbage collection can beachieved in the finalize blockby assigning its this referenceto a static field. But since a finalizer is called only once, an objectcan be resurrected just once. Eligibility for garbage collection if reference variable of that object isset to null and no otherreference is referring to it if reference variable of that object ismade to refer to some other object and there is no other referencereferring to it locally created objects after the methodreturns, provided they are not exported out of the method (ie. returnedor thrown as exception) Since there is no guarantee that the garbagecollector will ever run, there is also no guarantee that the finalizerwill ever be called. Also no guarantee of the order in which theobjects will be collected. System.gc()can be used to request garbage collection System.runFinalization()method can be called to suggest that any pending finalizers berun for the objects eligible for garbage collection. A Java application can use a Runtimeobject15 to interact with the JVM.Some methods include void gc()void runFinalization()long freeMemory()long totalMemory() Static Initializer Blocks are primarilyused to initialize static fields and consists of the keyword staticfollowed by a local block. When a class is initialized, the initializerexpression in static field declarations and static initializer blocksare executed in the order they are specified in the class. Instance initializer blocks can be usedto initialize fields during object creation. It merely consists of alocal block. The code in the block is executed every time an instanceof the class is created. TopThreads Defined by either extending java.lang.Thread or by implementing java.lang.Runnable interface. The run() method needs to be overridden.This method must be public and void and should take no arguments. Extending class MyThread extends Thread {public void run() {/* ... */}}You never call run() directly.Instead you call the start()method of the Thread class. MyThread my = new MyThread();mt.start(); Implementing class MyRunnable implementsRunnable {public void run() {/* ... */}}Here you construct a thread by passing the instance of the Runnable class as an argument. MyRunnable mc = new MyRunnable();Thread t = new Thread(mc);t.start(); Thread Constructorsavailable Thread() Thread(Stringname) Thread(Runnablerunnable) Thread(Runnablerunnable, String name) Thread(ThreadGroupg, Runnable runnable) Thread(ThreadGroupg, Runnable runnable, String name) Thread(ThreadGroupg, String name) wait(), notify and notifyAll() have to be called from a synchronized context. A dead thread cannever enter any other state, even if the start() method is called on it. yield() method causes the currentthread to move from the running to the runnable state to give otherthreads a chance to run. When a thread calls join() on another thread, thecurrently running thread will wait until the thread it joins with hascompleted. The argument to a synchronized keyword (in the case ofblocks) is the reference of the object to be synchronized on. In thecase of methods, the synchronizedkeyword merely precedes the method. Invoking start() twice on the same thread willthrow an IllegalThreadStateExceptionat runtime. TopFundamentalClasses The Mathclass is final and all methodsdefined in the Math class are static. This means you cannot inheritfrom the Math class andoverride the methods. Also, the Mathclass has a private constructorso you cannot instantiate it. ceil(), floor() and random() return double values. round() returns a long for doubleinputs and int for float inputs. Trigonometric methods takeradians as arguments, so we use Math.toRadians(). All wrapper classes except Character have two constructors– one that takes the primitive value and another that takes the String representation of the value. Character takes char type as argument. Wrapper objects areimmutable. All wrapper classes(except Character ) define a static method valueOf()which returns the wrapper object corresponding to the primitive valuerepresented by the String argument. Then byteValue(), doubleValue(), floatValue(), intValue(), longValue(), shortValue()are used to get the primitive values from thewrapper classes. Parser methods may be used to short-circuit theprocess. They throw NumberFormatException. TopCollections andMaps Set HashSet TreeSet LinkedHashSet List Vector ArrayList LinkedList Map HashMap HashTable TreeMap LinkedHashMap Set cannot contain duplicate elements. Notordered (implementation : HashSet)SortedSet holds elements in sorted ascending order. (implementation :TreeSet) HashSet is not ordered or sorted. (constant time performancefor basic add and remove). TreeSet arranges the elements in ascending element order,sorted according to the natural order of the elements. LinkedHashSet is an ordered HashSet, which gives elements inthe order of insertion or last access. List represents ordered collections which allowpositional access and search and can contain duplicate elements.(implementation : LinkedList, ArrayList, Vector, Stack) ArrayList enables fast iteration ad constant speedpositional access. Vector is similar to ArrayList only slower since it issynchronized. LinkedList allows fast insertion and deletion at thebeginning or end. Commonly used for implementing stacks and queues. Stack is subset of Vector, it is simple LIFO. Map matches unique keys to values. Each key mapsto at most one value. It does not implement the Collection interface(implementation : HashMap, HashTable, WeakHashMap)SortedMap orders the mapping in the sorted order of keys. HashMap is not sorted or ordered. It allows one null key andmany null values. HashTable is similar to HashMap but does not allow null keysand values. Also, it is slower because it is synchronized. LinkedHashMap iterated by insertion or last accessed order.Allows one null key and many null values. TreeMap is a map in ascending key order, sorted according tothe natural order for the key's class. Two objects that are not equal can have the samehash code. The hash code of a null value is defined as zero. When you override equals() you should overridehashCode()16 but the reverse is notrequired. A BitSet is not part of the CollectionsFramework. It contains elements which are bits (ie. boolean primitive).Like Vector its not of fixed size and can grow as needed. TopListof ReferencesAthorough reading of the following is highly recommended, much of theinfo in the notes is from them.[1]“A Programmer's Guide to Java Certification, SecondEdition”- Khalid A. Mughal and Rolf W. Rasmussen.PearsonEducation[2] “JavaCertificationSuccess, Part 1 SCJP”IBMdeveloperWorks[3] “Sun CertifiedJavaProgrammer Pre-Exam Essentials” - Dylan Walsh[4] “Java Tips”-Heather MacKenzieDisclaimersNo claims are made about theaccuracy of this document and no responsibility is taken for anyerrors. The original author cannotcontrol, and may not be aware of, derived versions of the document.Copyright© 2005 Rohit George.Permissionis granted to copy, distribute and/or modify this documentunderthe terms of the GNU Free Documentation License, Version 1.2orany later version published by the Free Software Foundation;withno Invariant Sections, no Front-Cover Texts, and no Back-CoverTexts. A copy of the license is included in the section entitled“GNUFreeDocumentation License”.1That means the variable must be declared final for implicit narrowing to takeplace.2String,Date and wrapper classesoverride equals(). StringBuffer does not.3Where elementtype 2 must be assignable to type 1.4The list cannot contain the array name.5Since the static context is not executedin the context of any object.6For example java.lang.Cloneable, java.io.Serializable, java.util.EventListener7They inherit from Exception8System classes are those in java.* packages9In the case of Overloading return type mayvary.10Somewhat clashing with the subset idealin exceptions.11Instance members are overridden.Instance variables, staticmethods and static variablesare hidden.12Can only be nested within other static members or top-level classesand interfaces.13Cannot have static members.14Cannot be specified with the keyword static.15Obtained by calling Runtime.getRuntime()16Which returns intTopFor a PDF version of this document, click here SCJP1.4 Guide(PDF)To Download Acrobat Reader to read the PDF, clickhere AcrobatReaderSunCertified Programmer for Java 2 Platform 1.4(c) 2005 Rohit George |
|