java test objectives 2

Upload: sahil-bansal

Post on 06-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Java Test Objectives 2

    1/48

    Java Programmer Certification Objectives

    Author Narayanan JDate 2nd Jun 99Version 1.0

    Page 1 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    2/48

    Java Programmer Certification Objectives

    1 Language Fundamentals

    Objective 1.1Use standard "javadoc" format documentation to identify and use

    variables and methods in classes. Employ such documentation to identifyvariables and methods that are inherited from a superclass.

    Objective 1.2

    Distinguish legal and illegal orderings of package declarations, import

    statements, public class declarations, and non-public class declarations.

    package packname;import lib1;[import lib2;]....class declaration

    Page 2 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    3/48

    Java Programmer Certification Objectives

    Note : package packname; must be the first non comment statement

    Objective 1.3

    State the correct declaration for a main() method

    The signature or format of the main method is

    public static void main(String argv[]);

    Note : The ordering of public and static are not important.static public void main(String argv[]) is valid

    The return type of any method is mandatory and must come before thename of the method.

    public void static main(String argv[])//Error will not compile

    Objective 1.4

    Select specific elements from the command line arguments of the main()method by using the correct array subscript value.

    java program parm1 param2argv[0] --> param1argv[1] --> param2

    Objective 1.5

    Identify Java keywords from a list of keywords and non-keywords.( const / goto)

    Objective 1.6

    Determine the value of a member variable of any type when no explicitassignment has been made to it.

    A class level variable will always be assigned a default value.A varialbe local to a method will not be assigned a default value.

    Objective 1.7

    Page 3 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    4/48

    Java Programmer Certification Objectives

    Determine the value of an element of an array of any base type, whenthe array has been constructed but no explicit assignment has been made tothe element.

    The value of the elements of an array of any base type will always beinitialised to a default value, wherever the array is defined. It does not matterif the array is defined at class or method level, the values will always be setto default values.

    Objective 1.9

    State the range of primitive data types byte, short, int, long and char.

    Objective 1.10

    Distinguish between legal and illegal identifiers

    Identifiers must start with a letter or a $ or _ character. The body of anidentifier cannot contain spaces, and must be letters, digits, underscores ordollar signs.

    Objective 1.11

    Construct literal numeric values using decimal, octal and hexadecimalformats.

    To represent a number as hexadecimal it is preceded by either : 0X or0x

    To represent a number as octal it is preceded by : 0

    Objective 1.12

    Construct literal String values using quoted format.

    String name = "Narayanan"

    Objective 1.13

    Construct a literal value of char type using Javas unicode escape format fora specified character code.

    Page 4 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    5/48

    Java Programmer Certification Objectives

    char c = 'n' ; char cc='\u0020';// space

    2: Operators and assignments

    Objective 2.1

    Determine the result, in terms of a bit pattern, of applying the >>, >>>and

  • 8/3/2019 Java Test Objectives 2

    6/48

    Java Programmer Certification Objectives

    Generally there is little difference between these two ways of creatingstrings, but the Exam may well ask questions that require you to know thedifference.

    The creation of two strings with the same sequence of letters without the useof the new keyword will create pointers to the same String in the Java String

    pool. The String pool is Javas way of conserving resources. To illustrate theeffect of this

    String s = "Hello";String s2 = "Hello";

    if (s==s2){

    System.out.println("Equal without new operator");}String t = new String("Hello");string u = new String("Hello");if (t==u){System.out.println("Equal with new operator");}

    From the previous objective you might expect that the first output "Equalwithout new operator" would never be seen as s and s2 are different objects,

    and the == operator tests what an object points to, not its value. Howeverbecause of the way Java conserves resources by re-using identical stringsthat are created without the new operator s and s2 have the same "address"and the code does output the string

    "Equal without new operator"

    However with the second set of strings t and u, the new operator forces Javato create separate strings. Because the == operator only compares theaddress of the object, not the value, t and u have different addresses and thus

    the string "Equal with new operator" is never seen.

    The business of the use of the String pool and the difference between the useof == and the equals method is not obvious, particularly if you have a VB

    background. The best way to understand it is to create some examples foryourself to see how it works. Try it with various permutations of identicalstrings created with and without the new operator.

    Page 6 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    7/48

    Java Programmer Certification Objectives

    The requirement to understand the use of the equals operator onjava.lang.Boolean is a potential gotcha. Boolean is a wrapper object for theboolean primitive. It is an object and using equals on it will test

    According to the JDK documentation the equals method of the Booleanwrapper class "Returns true if and only the argument is not null and is aBoolean object that contains the same boolean value as this object".

    egBoolean b1 = new Boolean(true);Boolean b2 = new Boolean(true);if(b1.equals(b2)){

    System.out.println("We are equal");}As a slight aside on the subject of boolean and Boolean, once you arefamiliar with the if operator in Java you will know you cannot perform thesort of implicit conversion to a boolean beloved of beardedC/C++

    programmers.int x =1;if(x){//do something, but not in Java

    }This will not work in Java because the parameter for the if operator must bea boolean evaluation, and an Java does not have the C/C++ conceptwhereby any non null value is considered to be true. However you maycome across the following in Java

    boolean b1;if(b1){//do something in java}

    Although this is rather bad programing practice it is syntactically correct, asthe parameter for the if operation is a boolean.

    Objective 2.5

    In an expression involving the operators &,|,&&, and || state whichoperands are evaluated and determine the resulting value of the expression.

    Page 7 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    8/48

    Java Programmer Certification Objectives

    Objective 2.6

    Determine if an assignment is permitted between any two variables ofpossibly different types.

    Objective 2.7

    Determine the effect of assignment and modification operations uponvariables of any type.

    3 : Declarations and Access Control

    Objective 3.1)

    Declare variables of type "array of X" for any type X. Identify thelegal positions for the "[ ]" part of an array declaration.

    The declaration of an array does not allocate any storage, it justannounces the intention of creating an arryay. As noticed with the signatureof the main method arguments, the square backets can comeafter the data type or after the variable name. Thus these are equivalent

    int[] i; and int i[];

    Note that you do not provide a number or variable to indicate the size ofarray at the point of declaration..

    An array declaration can have multiple sets of square brackets. Javadoes not formally support multi dimensional arrays, however it does supportarrays of arrays, also known as nested arrays.

    The important difference between multi dimensional arrays, as in C/C++ and nested arrays is that each array does not have to be of the same length.

    If you think of an array as a matrix, the matrix does not have to be arectangle. According to the JLS

    "The number of bracket pairs indicates the depth of array nesting."

    In other languages this would correspond to the dimensions of anarray. Thus you could set up the sqares on a map with an array of 2

    Page 8 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    9/48

    Java Programmer Certification Objectives

    dimensions thusint i[][];The first dimension could be X and second Y coordinates.

    Objective 3.2

    Construct arrays of any type.

    An array is actually created in memory by using the new keyword andspecifying its dimensions. Thus for an array of integers with 8 elements youcould declare and create a reference to it as follows.

    in[] j;j=new int[8];you could also do both operations in one statement

    int I[]=new int[8];Note that the sqare brackets were placed after the variable name in thesecond instance, they could just have correctly been placed after thedata type as in int[] I=new int[8];

    The number in the brackets that specifies the dimension (8 in theprevious example), can be a can be a constant, as in this case, or any integervariable.

    Thus the previous example could have been created as

    int p=8;int I[]=new int[p];

    Objective 3.3

    Write code to intialize an array using loop iteration.

    Arrays in java allways know how big they are, and this is representedin the length field. Thus you can dynamically populate an array with thefollowing code.

    int myarray[]=new int[10];for(int j=0; j

  • 8/3/2019 Java Test Objectives 2

    10/48

    Java Programmer Certification Objectives

    fixed at the time of creation and cannot be changed.

    Objective 3.4

    Write code to initialize an array using the combined declaration andinitialization format.

    Instead of looping through an array to perform initialisation, an arraycan be created and initialised all in one statement. This is particularlysuitable for small arrays. The following will create an array of integers and

    populate it with the numbers 0 through 4.int k[]=new int[] {0,1,2,3,4};

    Note that at no point do you need to specify the number of elements in

    the array. You might get exam questions that ask if the following iscorrect.

    int k=new int[5] {0,1,2,3,4} //Wrong, will not compile!

    You can poplulate and create arrays simultaneously with any data type, thusyou can create an array of strings thus.

    String s[]=new String[] {"Zero","One","Two","Three","Four"};

    The elements of an array can be addressed ust as you would in C/C++ thusString s[]=new String[] {"Zero","One","Two","Three","Four"};System.out.println(s[0]);This will output the string Zero

    Objective 3.5

    Define clases, including member variables and member methods.

    Classes are the building blocks of Java. There is no such thing as stand

    alone code in Java, all executable code is a part of a class, and to executethe code a class must be "instantiated", ie a copy created in memory.

    As a slight contradiction to that last statement, Java does support the statickeyword to allow code to run without instantiating an object. This is used inevery java program for the main event, thus the signature of main is

    public static void main(String argv[])

    Page 10 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    11/48

    Java Programmer Certification Objectives

    Classes are defined with a access keyword, the class keyword and a namefor the class. Thus a class can be defined as

    public class classname {}

    This is a legally defined class with no variables, or methods that willcompile.

    The methods and variables are the guts of a java applications. They arethe executable code that is called as part of an object to "do things".ThusJava provides the built in static object System.out which has the printlnobject that lets you send output to the console.

    The signature of a method must include a return type, but that type canbe void indicating that the method does not return a value. The return type

    must come before the name of the method. Thus

    public int amethod(int I)is legal butint public amethod(int I) //NOT LEGAL!!is not legal

    Objective 3.6

    Declare classes using the modifiers public, abstract or final.

    Only one class in any file can be defined with the public key word. Ifyou define more than one class in a file with the keword public the compilerwill generate an error. A public class has global scope, and an instance can

    be created from anywhere within or outside of a program.

    An inner class can be defined as private but a Top level (ordinary, notnested) cannot.

    A private class is only accessible from its enclosing class and other

    classes declared within its enclosing class.

    An abstract class canot itself be instantiated. To get at the functionalityof an abstract class it must be subclassed.

    The final modifier could be viewed as the opposite of abstract, in that afinal class cannot be subclassed. This prevents other programmers from

    Page 11 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    12/48

    Java Programmer Certification Objectives

    creating children of a class. The standard java classes include manyexamples of final classes. An example is the String class. You cannot addnew methods to the string class. You can however create a new class thatcontains a String and add your own methods and field to that class.

    Objective 3.7

    Declare vairables using the modifiers private, protected, public, static,final, native or abstract.

    The first three modifiers, private, protected and public control thevisibility of variables, ie what code can see their contents.

    protected

    A protected variable is visible within a class, and in sub classes, thesame package but not elsewhere. The qualification that it is visible from thesame package can give more visibility than you might suspect. Any class inthe same directory is considered to be in the default package, and thus

    protected classes will be visible. This means that a protected variable ismore visible than a variable defined with no access modifier. A variabledefined with no access modifier is said to have default visibility. Defaultvisibility means a variable can be seen within the class, and from elsewherewithin the same package, but not from sub-classes that are not in the same

    package.

    static

    static variables are always initalised to default values, in the same waythat class level variables are initialised. Static variables are also known asclass variables because there can be no more than one copy of each staticvariable associated with the class. Thus although you might have multipleinstances of the class there will only ever be one instance of any staticvariable.

    private

    Private variables are only visible from within the same class they arecreated. This means they are NOT visible within sub classes Publicvariables, as you might guess are visible from just about anywhere.

    Page 12 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    13/48

    Java Programmer Certification Objectives

    Objective 3.8

    State the prototype of the default constructor. List the circumstanceswhich govern creation of a default constructor.

    This objective is the sort that might catch out an experienced Javaprogrammer.

    The prototype of the default constructor is to have no arguments.The default constructor is created when a class has NO explicit

    constructors.

    If you don't define a constructor for a class and then you create a subclass, java inserts an implicit no args default constructor. So although it may

    look as if a class has no constructor, behind the scenes java is inserting aninvisible constructor that takes no arguments and doesn't do anything.

    So what you might ask,well it can trip you up If you have a class withno constructor you get used to creating instances of it withthout parameters.Thus

    MyClass mc=new MyClass();

    This is fine and dandy, but what happens when you decide that you

    need a version of it that takes some sort of constructor parameter. Now youhave a version of it that you create thus.

    MyClass mc=new MyClass(100);

    But any code that tries to create an instance of this class withoutconstructor arguments will now be broken. Java only inserts the defaultconstructor if a class has no other constructors. Of course you can get aroundthis problem by always creating a no args constructor for a class, so addingany other constructors later on will not cause a problem.

    Objective 3.9

    State the consequences, in terms of the results of an assignment to avariable, of the qualifiers static or final being applied to that variable.

    Only one instance of a static variable will ever exist per class. Thus if

    Page 13 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    14/48

    Java Programmer Certification Objectives

    multiple instances of a class are created and assignments are made to a staticvariable, those assignments will be visible from within other instances of theclass.

    Until Java 1.1 any final variable acted like a C/C++ constant. It had tobe initialized at the same time as it was declared and the value could not bemodified once it was created. Java 1.1 introduced the idea of blank finalvariables. This is a variable that is not assigned a value at declaration butonce it is assigned a value, such as in a constructor, that value cannot bechanged. There is no blank keyword, it is just a final declaration without anassignment, thus.

    final int iFin;

    The assignment of a variable is checked at compile time, and an errorwill be generated if no assignment is made.

    Objective 3.10

    State the effects on scope and accessibility of an instance variable ormethod of these factors:

    The calling method is staticThe calling method is non-static

    The calling method is in the same class as the targetThe calling method is in a subclass of the class containing the targetThe calling method is in a class which is in the same package as the

    class containing the targetNo special relationship exists between the class of the caller and the

    class of the targetThe target declaration is qualified by any of private, protected,

    public,static, final, or abstract.

    The calling method is static

    A static method cannot directly refer to other, non-static methods orvariables in its class

    Thus the following code will cause an error

    public class MyClass{

    Page 14 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    15/48

    Java Programmer Certification Objectives

    int instint=99;public static void main(String argv[]){System.out.println("reference to instint causes compile error");//mymethod();}static void mymethod(){instint +=100;//referring to a non static int will cause an//error, even without a method call}}This code will cause an error along the lines ofError non-static variable canot be referenced from a static context

    The calling method is non-static

    A non static calling method is an "ordinary" method, an instancevariable can be manipulated by a non-static method and the results will bevisible to other methods in the class.

    The calling method is in the same class as the target

    Instance variables can be manipulated by non-static methods in thesame class. No qualification is needed and no instance of the class need becreated. Thus

    public MyClass{int classint=99;public amethod(){classint +=10;System.out.println(classint);}

    The compiler sees an implicit reference to this before the reference tothe instance variable. It is as if the code read

    this.classint +=10;

    This version of the code will compile, and it says that you are referringto the copy of the variable in this instance of the class.

    The calling method is in a subclass of the class containing the

    Page 15 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    16/48

    Java Programmer Certification Objectives

    target

    Subclasses can refer to instance variables in parent classes as if theywere declared in the curent class. It is as if a sub class carries a hidden copyof the variable.

    No special relationship exists between the class of the caller and theclass of the target

    By no special relationship, I take it to mean that the variable is not inthe same package, class, or subclass to the calling method. If the instancemethod is declared to be public a method in an unconnected class will beable to refer to the variable and manipulate it using the fully qualified nameof the method.

    Take the following example

    package firstpackage;

    class firstclass{public int instint;}

    package secondpackage;class secondclass{

    public void amethod(){firstpackage.firstclass f=new firstpackage.firstclass();f.instint+=99;} }

    The target declaration is qualified by any of private, protected,public, static, final, or abstract.

    By target declaration this objective referrs to the method (you can'thave an abstract variable).

    4 Flow Control and Exception Handling

    Objective 4.1Write nested conditional code using the if, else and switch constructs.

    If/else constructs in Java are just as you might expect from other

    Page 16 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    17/48

    Java Programmer Certification Objectives

    languages. Switch/casestatements have a few peculiarities.

    The syntax for the if/else statement is

    if(boolean argument){//the boolean was true so do this}else {//do something else

    }

    Java does not have a "then" keyword like the one in Visual Basic.

    One idiosyncrasy of the Java if statement is that it must take a boolean

    value. You cannot use the C/C++ convention of any non zero value torepresent true, and 0 for false.

    The argument to a switch statement must be a byte, char, short or int.You might get an exam question that uses a floating float or long as theargument. A fairly common question seems to about the use of the breakstatement in the process of falling through a switch statement. Here is anexample of this type of question.

    int k=10;

    switch(k){case 10:System.out.println("ten");

    case 20:System.out.println("twenty");

    }

    Common sense would indicate that having executing the instructionsfollowing a case statement and having come across another case statementthe compiler would then finish falling through the switch statement.

    However for reasons best known to the designers of the language casestatements only stop falling through when they come across a breakstatement. As a result, in the above example both the strings ten and twentywill be sent to the output.

    Another little peculiarity that can come up on questions is the placingof the default statement. The conventional place for the default statement is

    Page 17 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    18/48

    Java Programmer Certification Objectives

    at the end of of case options. Thus normally code will be written as followsint k=10;switch(k){

    case 10:System.out.println("ten");

    break;case 20:

    System.out.println("twenty");break;

    default:System.out.println("This is the default output");

    }This approach mirrors the way most people think. Once you have tried

    the other possibilities, you perform the default output. However it is

    syntactically correct, if not advisable, to code a switch statement with thedefault at the top.

    int k=10;switch(k){default: //Put the default at the bottom, not here

    System.out.println("This is the default output");break;

    case 10:System.out.println("ten");

    break;case 20:System.out.println("twenty");

    break;}

    Objective 4.2

    Identify the legal expression types for the argument of if() andswitch().

    An if statement can only take a boolean type and a switch can onlytake a byte, char short or int.

    Objective 4.3

    Write nested loops to iterate blocks with specific values in loop

    Page 18 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    19/48

    Java Programmer Certification Objectives

    counter variables.

    The most common method of looping is to use the for statement. LikeC++ and unlike C the variable that controls the looping can be created andinitialised from within the for statement. Thus

    public class MyLoop{public static void main(String argv[]){MyLoop ml = new MyLoop();ml.amethod();}public void amethod(){

    for(int K=0;K

  • 8/3/2019 Java Test Objectives 2

    20/48

    Java Programmer Certification Objectives

    Demonstrate the flow of control that occurs in try, catch(), and finallyconstructions under

    conditions of normal execution, caught exception and uncaughtexception. The try and catch tatements are part of the exception handling

    built into Java. Neither C/ C++ nor Visual Basic have direct equivalents toJavas built in exceptions. C++ does support exceptions but they are optional,and VB supports On Error/Goto error trapping, which smacks somewhat ofa throwback to an earlier less flexible era of BASIC programming.

    Java exceptions are a built in part of the language. For example if youare performing IO you have to put in exception handling. You can of course

    put in null handling that doesn't do anything. The following is a little pieceof code I have used with Borland/Inprise Jbuilder to temporarily halt outputto the console and wait for any key to be pressed.

    import java.io.*;public class Try{

    public static void main(String argv[]){Try t = new Try();t.go();

    }//End of mainpublic void go(){

    try{DataInputStream dis = new DataInputStream(System.in);

    dis.readLine();} catch(Exception e){/*Not actually doing anything when exception occurs*/} //End of try

    System.out.println("Continuing");}//End of go

    }

    In this case nothing is done when an error occurs but the programmermust still acknowledge that an error might occur. If you remove the try and

    catch clause the code will simply not compile. The compiler knows that theio methods can causes exceptions and demands exception handling code.

    This is a little more rigorous than VB or C/C++ which allows you tothrow together "quick and dirty" programs that pretend they are in a worldwhere errors do not occur. Remember that the original version of DOS wascalled QDOS for Quick and Dirty DOS by it's creator and look how long we

    Page 20 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    21/48

    Java Programmer Certification Objectives

    have lived with the legacy of that bit of hackery. By the time you have goneto the trouble of putting in a try catch block and blank braces you may aswell put in some real error tracking. It's not exactly bondage and discipline

    programming, it just persuasively encourages you to do the right thing.

    The one oddity that you are likely to be questioned on in the exam isunder what circumstances the finally clause of a try/catch block is executed.The short answer to this is that the finally clause is almost always executed,even when you might think it would not be. Having said that, the path ofexecution of the try/catch/finally statements is something you really need to

    play with to convince yourself of what happens under what circumstances.

    One of the few occasions when the finally clause will not be executedis if there is a cause to

    System.exit(0);The exam tends not to try to catch you out with this exception.The exam is more likely to give examples that include return

    statements in order to mislead you into thinking that the code will returnwithout running the finally statement. Do not be mislead, the finally clausewill almost always run.

    The try/catch clause must trap errors in the order their natural order ofhierarchy. Thus you cannot attempt to trap the generic catch all Exception

    before you have put in a trap for the more specific IOException.

    The following code will not compiletry{

    DataInputStream dis = new DataInputStream(System.in);dis.read();}catch (Exception ioe) {}catch (IOException e) {//Compile time error cause}finally{}

    This code will give an error message at compile time that the more

    specific IOException will never be reached.

    Objective 4.6

    Write code that correctly uses the throws clause in a methoddeclaration where that method contains code that might throw exeptions.

    Page 21 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    22/48

    Java Programmer Certification Objectives

    Instead of handling errors at the point where they are likely to occur,the error can be passed up the call stack by use of the throws clause whendeclaring a method. Thus in the above example instead of surrounding thecalls to dis.read() with the try/catch clause the method declaration includesinformation on the type of exception that might be thrown. Thus the methodcalled go could be declared as

    import java.io.*;public class Try{

    public static void main(String argv[]){Try t = new Try();

    try{t.go();

    }catch(Exception e) {}

    }//End main methodpublic void go() throws Exception{DataInputStream dis = new DataInputStream(System.in);dis.read();

    }//End go method}//End of class

    Objective 4.7

    State what exceptions may be legitimately thrown from an overriding

    method in a subclass, based on the declaration of the overidden supperclassmethod.

    An overriding method in a subclass may only throw exceptionsdeclared in the parent class or children of the exceptions declared in the

    parent class. This is only true for overriding methods not overloadingmethods. Thus if a method has exactly the same name and arguments it canonly throw exceptions declared in the parent class or exceptions that arechildren of exceptions in the parent declaration. It can however throw feweror no exceptions.

    Objective 4.8

    Write code to create and throw a specified exception.

    The keyword to throw an exception unsurprisingly is throw. Thusinstead of waiting for the environment to trip an exception code logic can be

    Page 22 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    23/48

    Java Programmer Certification Objectives

    written to throw a new Exception. The user created exception is createdusing the new keyword. Thus if you were checking to see if an objectreference was valid you might create code such as

    if (myRef == null )throw new NullPointerException();

    5: Overloading, Overriding, Runtime Type, and Object Orientation

    Objective 5.1

    Write classes that implement object oriented relationships specifiedusing the clauses 'is a' and 'has a'.

    This is a very basic OO question and you will probably get a questionon it in the exam. Essentially it seeks to find out if you understand whensomething is referring the type of class structure that an object belongs toand when it referrs to a method or field that a class has.

    Thus a cat IS A type of animal and a cat HAS a tail. Of course thedistinction can be blurred. If you were a zoologist and knew the correctnames for groups of animal types you might say a cat IS A long latin wordfor animal group with tails.

    but for the purpose of the exam this is not a consideration.

    Objective 5.2

    Determine at run time if an object is an instance of a specified class orsome subclass of that class using the instanceof operator.

    Note that instanceof is an operator not a method. The syntax is likeusing the == operator.

    if (mc instanceof Object ){System.out.println("Like everything I am a decendent of Object");}

    Objective 5.3

    Distinguish between overloaded and overridden methods.

    Page 23 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    24/48

    Java Programmer Certification Objectives

    Overloaded

    The terms overloaded and overridden are similar enough to give causefor confusion. My way of remembering it is to imagine that something that isoverriden has literally been ridden over bya hevy vehicle and no longerexists in its own right. Something that is overloaded is still moving but isloaded down with lots of functionality that is causing it plenty of effort. Thisis just a little mind trick to stinguish the two, it doesn't have any bearing ofthe reality of the operations in java.

    Overloading of methods is a compiler trick to allow you to use thesame name to perform different actions depending on parameters.

    Thus imagine you were designing the interface for a system to runmock java certificate exams (who could this be?). An answer may come inas an integer, a boolean or a text string. You could create a version of themethod for each parameter type and give it a matching name thus.

    markanswerboolean(boolean answer){}markanswerint(int answer){}markanswerString(String answer){

    }

    This would work but it means that future users of your classes have tobe aware of more method names than is strinctly necessary. It would bemore useful if you could use a single method name and the compiler wouldresolve what actual code to call according to the type and number of

    parameters in the call.

    This is the heart of overloading methods, part of what is known ispolymorphism.

    There are no keywords to remember to override methods, you justcreate multiple methods with the same name but different numbers and ortypes. The names of the parameters are not important but the number andtypes must be different. Thus the following is an example of an overloadedmarkanswer method

    Page 24 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    25/48

    Java Programmer Certification Objectives

    void markanswer(String answer){}void markanswer(int answer){}

    The following is not an example of overloading and will cause acompile time error indicating a duplicate method declaration.

    void markanswer(String answer){}void markanswer(String title){}

    The return type does not form part of the signature for the purpose of

    overloading. Thus changing one of the above to have an int return value willstill result in a compile time error, but this time indicating that a methodcannot be redefined with a different return type. Overloaded methods do nothave any restrictions on what exceptions can be thrown. That is somethingto worry about with overriding.

    Overriding

    Overriding a method means that its entire functionality is beingreplaced.

    Overriding is something done in a child class to a method defined in aparent class. To override a method a new method is defined in the child classwith exactly the same signature as the one in the parent class. This has theeffect of shadowing the method in the parent class and the functionality is nolonger directly accessible.

    Java provides an example of overriding in the case of the equalsmethod that every class inherits from the granddady parent Object. Theinherited version of equals simply compares where in memory the instanceof the class referenfces. This is often not what is wanted, particularly in the

    case of a String. For a string you would generally want to do a character bycharacter comparison to see if the two strings are the same. To allow for thisthe version of equals that comes with String is an overriden version that

    performs this character by character comparison.

    Objective 5.4

    Page 25 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    26/48

    Java Programmer Certification Objectives

    State the legal return types for an overloading method given theoriginal method declaration.

    The return type does not form part of the signature for the purpose ofoverloading. Thus an overloaded method may return any data type.

    Objective 5.5

    State legal return types for an overriding method given the originalmethod declaration.

    The return type does matter for the purposes of overriding. Anoverriden method must have exactly the same return type as the method inthe parent class it is replacing. If you attempt to create an overriden method

    with a different return type you will get a duplicate method error at compiletime.

    Objective 5.6

    Describe the effect of invoking overridden method in base and derivedclasses.

    If a method is overriden (replaced by a method with identicalsignature), the version in the base class can still be invoked from an

    instance of the base class. Take the following exampleclass Base{public void amethod(){System.out.println("Base method")'}}public class Sub extends Base{public static void main(String argv[]){Sub s = new Sub();s.testmethod();

    }public void amethod(){System.out.println("Sub amethod")'}

    public void testmethod(){Base b = new Base();

    b.amethod()

    Page 26 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    27/48

    Java Programmer Certification Objectives

    }}The invocation of b.amethod() will cause the version of the method in

    the base class to be run and the output will beBase method();If the call to amethod had not been prefixed with the instance of Base

    b, then overriden version of the method in the derived class Sub would havebeen called and the output would have read, Sub amethod

    Objective 5.7

    Write code for any overriden method that invokes the parental method,using super.

    Rather than creating an instance of the base class you can directly callthe original version of an overriden method by using the super keyword. Touse this with the example in the previous section you could call

    super.amethod();If you consider this to be a call to a parent version of a method, there is

    no direct way of invoking a grandparent versionof a method.

    So you cannot do thissuper.super.super.amethod() //Not legal won't work

    Objective 5.8

    Write constructor bodies using this() and super() to access overloadedor parent-class constructors.

    The this keword causes an explicit reference to the current object.Whenever you refer to the current object there is an implicit reference to thethis object.You can try modifying code to see that prefixing variables withthis in non static code does not cause an error. Where the this reference

    cancome in useful is to access more than one version of a constructor. In thefollowing example the instance of Try is created with the String constructor,

    but within the String constructor is a call to the int version of the constructorby using this as a constructor thus

    this(99);public class Try{static int j=99;

    Page 27 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    28/48

    Java Programmer Certification Objectives

    public static void main(String argv[]){Try t = new Try("Hello ");}Try(int k){

    j +=k;}Try(String s){//Calling the other constructor for this classthis(99);System.out.println(s + j);}}

    Objective 5.9

    Define a non-static inner class either in a class or method scope.

    Inner classes were introduced with JDK 1.1 and were somewhatcontroversial, as you can tell by perusing the java.* newsgroups. Innerclasses give the programmer the convenience of nesting related classeswithin one source file. You cannot be in a position of not having anassociated class available.

    Rather than poke all of the bytecode into one file with the name of the

    outer class the java compiler produces a *.class output file with formatOuterClassName$InnerClassName

    An example of a top level inner class (ie not in method scope) is asfollows

    public class MyOuter{class MyInner {}}One of the most common uses is for adapters for event handling. An

    inner class is defined just like an outer class except it comes within the

    enclosing brackets of another class. Inner classes can also be defined withinthe enclosing braces of a method.

    Objective 5.10

    Define, in method scope, an anonymous inner class that implements aspecified interface.

    Page 28 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    29/48

    Java Programmer Certification Objectives

    An anonymous class has no name (surprise surprise). Instead of thesyntax

    ClassType ClassName = new ClassType()

    an anonymous inner class takes the form

    methodname (){new ClassType(){ //Class Body}};

    The following example is an example of an anonymous inner class thatimplements the runnable interface used with threads.

    public class MyOuter {public void amethod(){new Runnable() {

    public void run() {}};}}

    Note that although the anonymous class implements an interface it

    does not need to use the implements word as you would with a namedclass.

    Because there is no name for the class it looks a little like an attempt toinstantiate an interface, which is not allowed in Java.

    Objective 5.11

    Write code in a non-static method of the outer class to construct aninstance of the inner class.

    There is no catch to this objective, you can construct an instance of aninner class just as you would expect. The following code performs thiswithin a method.

    public class MyClass1 {public static void main(String argv[]){

    Page 29 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    30/48

    Java Programmer Certification Objectives

    MyClass1 mc = new MyClass1();mc.amethod();}public void amethod(){MyInner mi = new MyInner(); //Construction of instance of inner class}class MyInner { }//Inner class}

    Objective 5.12

    Write code to construct an instance on an inner class where either nothis object exists, or the current this object is not an instance of the outerclass.

    This objective involves using a slightly pecuilar syntax that you willprobably rarely use in the real world. For this reason it may be somethingyou will need to rote leaarn and make a point of memorising. In a staticmethod such as main there is no current this object. To allow for creation ofan instance of an inner class without reference to the this object you can usethe new operator as if it were a method of a class. The syntax is as follows

    public class MyClass1 {public static void main(String argv[]){

    MyClass1.MyInner mi = new MyClass1().new MyInner();}class MyInner { }}

    Objective 5.13

    State which variables and methods in enclosing scopes are accessiblefrom methods of the inner class.

    A non static inner class has an implicit reference to the this instance ofits enclosing class. Therefore it can access any variable of the enclosingclass.

    An inner class can be marked as static, ie it is not associated with anyinstance of the outer class, just like a static method is not associated withany particular instance of its enclosing class.

    Page 30 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    31/48

    Java Programmer Certification Objectives

    Because it is not associated with any instance of the outer class itcannot access any instance variable of the enclosing class. Of course it canaccess static variables because there will only ever be one instance of a staticvariable, no matter how many instance of the outer class is created.

    An inner class can be defined within a method, iepublic void amethod(){class methclass{}}

    In this case the enclosing scope is the method. Because variables atmethod level come into scope as the method executes there is a rulegoverning how the method level class can access the variables of the

    enclosing method. A class defined within a method can only access variablesat the level of the enclosingmethod if they have been defined as final. This includes variables passed as

    parameters to the enclosing method.

    Thus the following will compile, but if that parameter to amethod werenot defined as final, a compile time error would occur.

    public void amethod(final int z){MyInner mi = new MyInner();

    class methclass {public void mtm(){System.out.println(z);} } }

    It is only method level variables that are affected by this rule, a classdefined within a method has access to variables defined at the level of theenclosing class.

    6: Garbage Collection

    Objective6.1Distinguish between guaranteed and non-guaranteed behavior of the

    garbage collection and finalization mechanisms.

    You can be a very experienced Java programmer and yet may never

    Page 31 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    32/48

    Java Programmer Certification Objectives

    had to familiarise yourself with the details of garbage collection. One of thegreat touted beauties of the language is that you don't have to worry aboutgarbage collection. Unlike C/C++ Java automatically frees up unusedreferences. You don't have to go through the pain of searching forallocations that are never freed and you don't need to know how to alloc asizeof a data type according to the platform. So why would you want toknow about the details of garbage collection. Two answers spring to mind,one is to pass the exam and the other is to understand what goes on inextreme circumstances. If you write code that create very large numbers ofobjects or variables it can be useful to know when references are released. Ifyou read the newsgroups you will see people reporting occasions of certainJava implementations exhausting memory resources and falling over. Thiswas not in the brochure from Sun when the launched Java.

    In keeping with the philosophy of automatic garbage collection youcan suggest or encourage the JVM to perform garbage collection but youcant force it.

    At first glance finalisation sounds a little like the destructors in C++used to clean up resources before an object is destroyed. The difference isthat Java internal resources do not need to be cleaned up during finalisation

    because the garbage collector looks after memory allocation. However if youhave external resources such as file information finalisation can be used tofree external resources.

    Garbage collection is a tricky one to write exercises with or practicewith as there is no obvious way to get code to indicate when it is availablefor garbage collection. You cannot write a piece of code with a syntax like

    if(EligibleForGC(Object){System.out("Ready for Garbage");}

    Because of this you just have to learn the rules. To re-state.

    Once a variable is no longer referenced by anything it is available forgarbage collection.

    You can suggest garbage collection with System.gc(), but this does notguarantee when it will happen

    Page 32 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    33/48

    Java Programmer Certification Objectives

    Objective 6.2

    Identify the earliest point in a method at which the object referred to by alocal variable is definitely eligible to be garbage collected, in the absence ofcompiler optimization.

    Local variables in methods go out of scope when the method exits. Atthis point the methods are eligible for garbage collection. Each time themethod comes into scope the local variables are re-created.

    7 : Threads

    Objective 7.1

    Write code to create a new thread of execution, using both theRunnable interface and the Thread class.

    Threads are lightweight processes that appear to run in parallel withyour main program. An example of where they can be useful is in printing.When you click on a print button it would be very handy if the printing

    process started running but allowed you to continue using the main portionof the program. It would also be useful if the main program wouldrespond if the printing thread encountered a problem. A common exampleused to illustrate threads is to create a gui application that launches a

    bouncing ball every time a button is clicked. Unlike most language threadingis embedded at the heart of the Java language, much of it at the level ofthe ultimate ancestor class called Object.

    Of the two methods of creating a new thread the use of runnable isprobably more common, but you must know about both. Here is an exampleof a class created with the runnable interface.

    class MyClass implements Runnable{public void run(){}

    }

    Creating the thread of execution.MyClass mc = new MyClass();

    I include the method run even in this little example, because you mustinclude a run method if you implement runnable. Not including a run method

    Page 33 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    34/48

    Java Programmer Certification Objectives

    will cause a compile time error.

    The other method for creating a thread is to create a class that isdescended from Thread. This is easy to do but it means you cannot inheritfrom any other class, as java only supports single inheritance.

    Objective 7.2

    State the requirements for a concrete class that is declared toimplement the java.lang.Runnable interface.

    Any class that is implements an interface must create a method tomatch all of the methods in the interface. The methods need not do anythingsensible, ie they may have blank bodies, but they must be there.

    public void run(){//Blank body}

    This is the one method in the runnable interface. You must include thisin any class that implements the runnable interface. To do anything usefulwhen you create a thread of execution from a class you would, of courseneed to put something where I have put //Blank Body.

    Objective 7.3

    Name the method that provides the starting point for execution of a

    thread. ( run )

    Objective 7.4

    Write code to start the execution of a thread.

    Although the code that runs in your thread is in a method called run,you do not call this method directly, instead you call the start method of thethread class. The runnable interface does not contain a start method, so toget at this and the other useful methods for threads (sleep, suspend etc etc),

    you passyour class with the runnable interface as the constructor to an instance of theThread class.

    Thus to cause the thread to execute from a class that implementsrunnable you would call the following

    Page 34 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    35/48

    Java Programmer Certification Objectives

    MyClass mc = new MyClass();Thread t = new Thread(mc);t.start();

    Again note that was a call not start, not a call to run, even though it isthe code in the run method in your class that actually executes.

    If you create your class as a sub class of Thread you can simply callthe start method. The drawback of sub classing the Thread class is that dueto only supporting single inheritance you cannot inherit the functionality ofany other class.

    Objective 7.5

    State and recognize conditions that might prevent a thread from

    executing.

    The expression "prevent a thread from executing" is slightlyambiguous, does it mean a thread that has been deliberately paused, or doesit also include threads that have died?. A thread that is prevented fromexecuting is said to be blocked.

    a thread may be blocked because1) it has been put to sleep for a set amount of time2) It is suspended with a call to the suspend() method and will be

    blocked until it gets sent the resume message3) The thread has been suspended by call to wait(), and will not become runnable again until it gets a notify or notifyAll message.

    4) The thread is waiting for some IO to complete5) The thread is calling another synchronized method that is not

    available.

    For the purposes of the exam sleep(), suspend and wait/notify areprobably the most important of the situations where a thread can be blocked.

    Objective 7.6

    Write code to use the synchronized keyword to require a thread ofexecution to obtain an object lock prior to proceeding.

    The synchronized keyword can be used to mark a statement or block ofcode so that only one thread may execute an instance of the code at a time.

    Page 35 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    36/48

    Java Programmer Certification Objectives

    Entry to the code is protected by a monitor lock around it.

    For a method the synchronized keyword is placed before the methodthus

    synchronized void amethod() { /* method body */}

    For a block of code the synchronized keyword comes before openingand closing brackets thus.

    synchronized (ObjectReference) { /* Block body */ }

    The value in parentheses indicates the object or class whose monitorthe code needs to obtain.

    When a synchronized block is executed, its object is locked and itcannot be called by any other code until the lock is freed.

    synchronized void first();

    synchronized void second();

    There is more to obtaining the benefits of synchronization than placingthe keyword synchronized before a block of code. It must be used inconjunction with code that manages the lock on the synchronized code . This

    is covered in the objectives covering wait/notify/notifyAll.

    Objective 7.7

    Define the behavior of a thread which invokes the wait() method of anobject and the effect of that method on the object lock flag.

    Calling wait a thread from synchronized code causes a thread to give

    up its lock and go to sleep. This normally happens to allow another thread toobtain the lock and continue some processing. The wait method ismeaningless without the use of notify or notifyAll which allows code that iswaiting to be notified that it can wake up and continue executing.

    Objective 7.8

    Page 36 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    37/48

    Java Programmer Certification Objectives

    Define the behavior of a thread which invokes the notify() ornotifyAll() methods of an object and the effect of the method on the objectlock flag.

    The notify and notifyAll methods are inherited from the Object class.The notify method "wakes up a single thread that is waiting on this objectsmonitor". Unsurprisingly notifyAll "wakes up all threads that are waiting onthis objects monitor". The expression "waiting on this objects monitor"implies the use of the wait method (also contained in the Object class).

    Do not assume that because a thread has been woken up it musttherefore be running. Once woken up, these threads are in the ready state. Ifmore than one thread has been woken up and moved to the ready state,which one will actually execute?

    In one of the rare oversights in the java language the schedulingimplementation for threading was ffectively left vendor implemented. Thismeans that you cannot exactly predict how threads will react between onevendors version of java and another. You may even find differences betweenthe same vendor on different platforms.

    The two main approaches are pre-emptive scheduling and time-slicing

    For the purpose of the exam all you really need to know about this is

    that it is vendor and platform dependent and the exact way threads will workon different systems is not predictable.

    The use of notify and notifyAll is tied up in the following objectivewhich shows it in use along with wait.

    Objective 7.9

    Define the interaction between threads executing the wait(), notify(), ornotifyAll() methods, and the object lock flag.

    The wait/notify(All) protocol is useful where more than one programneeds to access data. If the update of information is not carefully controlledthe data may become inconsistent. To allow access to the data to besynchronized every object in each class has a monitor. Only one thread at atime can one an individual monitor.

    Page 37 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    38/48

    Java Programmer Certification Objectives

    Examples of threads often have apparently endless loops such as//producing codewhile(true){try{

    wait();}catch (InterruptedException e) {}

    }//some producing action goes herenotifyAll();As true is notorious for staying true this, code looks at first glance like

    it will just loop forever. The wait method however effectively means give upthe lock on the object and wait until the notify or notifyAll method tells youto wake up.

    This sort of looping code will be matched with a similar type ofconsuming code.

    In the Roberts and Heller chapter on threads they give two top keypieces of advice

    Always check the monitors state in a while loop rather than an ifstatement after changing the monitors state, call notifyAll() rather thannotify();

    The reason for the use of notifyAll is because notify does not allowyou to specify which thread should will be notified.8: The java.lang package

    Objective 8.1

    Write code to demonstrate the use of methods of the java.lang.Mathclass in an expression: abs(), ceil(), floor(), max(), min(), random(), round(),sin(), cos(), tan(), sqrt().

    Getting to grips with this objective is mainly a memory exercise. Ipersonally had to take a second look at the use of abs and you might get a aquestion that asks what the effect of ceil or floor on a negative number. Therandom function returns

    Objective 8.2

    Page 38 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    39/48

    Java Programmer Certification Objectives

    Write code to demonstrate the use of the following methods of thejava.lang.String class: length(), toUpperCase(), toLowerCase(), equals(),equalsIgnoreCase(), charAT(),concat(), indexOf(), stIndexOf(), substring(),toString(), trim().

    Objective 8.3

    State all operators that are legal in String expressions.

    Because Strings are objects you can only use Ob ject operators onthem. Thus you cannot use the mathemtatical operators to multiply, subtractor perform logical operations on Strings. You can however use the + sign toconcatenate two strings. Thus the following code will output the string

    Hello ThereString s1 = new String("Hello");String s2 = new String("There");System.out.println(s1+s2);

    Although Java does not allow users to overload operators as C++ does,the langage designers decided that being able to use the + sign with Stringswas too useful to leave out. If you are from a VB background, rememberthat you cannot use the ampersand (&) operator to concatenate two strings.

    Objective 8.4

    Recognize the implications of the immutability rule of the String class.

    The theory of the immutability of the string class says that oncecreated a string can never be changed. Real life experience with Java

    programming implies that this is not true.

    Take the following code

    String s1 = new String("Hello");String s2 = new String("There");System.out.println(s1);s1=s2;System.out.println(s1);

    If Strings cannot be changed then s1 should still print out Hello, but if

    Page 39 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    40/48

    Java Programmer Certification Objectives

    you try this snippet you will find that the second output is the string "There".What gives?

    The immutability really refers to what the String reference points to.When s2 is assigned to s1 in the example, the JVM creates a new string andthe reference s1 now points to this new string.

    The objective asks you to recognise the implications of theimmutability of strings, and the main one seems to be that if you want tochop and change the contents of "strings" the StringBuffer class comes withmore built in methods for the purpose.

    Because concatenating string causes a new string to be instantiated"behind the cenes", there can be a performance overhead if you are

    manipulating large numbers of strings, such as reading in a large text file.Generally String immutability doesn't affect every day programming.

    Section 9: The java.awt package

    Objective 9.1)

    Components and Facilities methods of the java.awt.Component class:setVisible(boolean), setEnabled(boolean), getSize(), setForeground()and setBackground().

    Objective 9.2

    Construct a java.awt.TextArea or java.awt.List that prefers to display aspecified number of columns.

    Objective 9.3

    Construct a java.awt.TextArea or java.awt.TextField that prefers todisplay a specified number of columns.

    Objective 9.4

    State the significance of a "column" where one of the text componentsis using a proportional (variable) pitch font or a fixed pitch font.

    For controls that have constructors that indicate a preffered number of

    Page 40 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    41/48

    Java Programmer Certification Objectives

    columns, the pitch of the current font will influence how many actual textcharacters will appear. Thus if you have a proportional font that contains astring with many "wide" wide characters in it such as W, it will be able todisplay fewer characters than if it was set to a monospaced, typwriter stylefont such as courier.

    Objective 9.5

    Identify the following as methods of the Graphics class: drawString(),drawLine(), drawRect(), drawImage(), drawPolygon(), drawArc(),fillRect(), fillPolygon(), fillArc().

    Objective 9.6

    Write code to obtain a suitable Graphics object from an Image.

    Within the paint method you could obtain a graphics context and drawthe image with the following code. Graphics g =MyImage.getGraphics();

    Objective 9.7

    Distinguish between situations that require the use of an Image objectfrom those that require the use of a Graphics object.

    You can get an idea of the situations that require an image or graphic ifyou use the analogy of a Graphic as a photographic film and the Image asthe idea, or framing of a photo to be taken on the film. You almost alwaysuse a Graphic with an Image but you may often use a Graphic without animage.

    The image class has methods for scaling and filtering a picture but notfor drawing new lines or areas on a picture. The image file does not have aconstructor but gets populated with its picture by using the getImage()

    method of Applet or , Toolkit in an application, or the createImage() methodof Component or Toolkit.

    A graphics object is needed in order to display an image object. Thegraphics method drawimage is used to actually draw the image on screen. Ithas the signature public abstract boolean drawImage (Image image, int x, inty, ImageObserver observer)

    Page 41 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    42/48

    Java Programmer Certification Objectives

    Situations where you might use a Graphics object without an Imageare if you were writing a graphing program and were drawing lines and

    points on an X/Yaxis. A typical situation where you would use a Graphicsand Image object together, was if you were creating a program to load aseries of jpg files onto a form for previewing.

    10 : The java.awt package - Layout

    Objective 10.1

    Demonstrate the use of the methods add(Component) and add(String,Component) of the java.awt.Container class and recognize which classes inthe java.awt and java.awt packages are valid arguments to these methods.

    Use of the add method is fairly straightforward. Typically the addmethod might be used asButton b = new Button("Hello");add(b);

    In this instance add is a method of the implicit "this" instance.

    Note that the documents for jdk1.1 say

    //Quote

    public Component add(String name, Component comp)Adds the specified component to this container. It is strongly advised touse the 1.1

    method, add(Component, Object), in place of this method.//EndQuote

    It is interesting to speculate why a strong recommendation is givenrather than a deprecation of he method.

    Any class that is a descendent of the Component class is a valid

    argument to the add method.

    Typically these are items that would be called controls in visual basic, ieButtons, TextFields, Labels, Lists etc.

    Objective 10.2

    Page 42 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    43/48

    Java Programmer Certification Objectives

    Distinguish between AWT classes which are directly responsible fordetermining component layout and those which are responsible forimplementing that layout.

    This objective seems to be strangely worded, but it appears to ask youto understand layout managers interact with components and containers todetermine the eventual appearance of an application or applet. Because Javalays great emphasis on cross platform capability, programs should present asimilar appearance all platforms. This is unlike systems such as VB orDelphi where the programmer can specify the position of components to the

    pixel level. Indeed, in VB creating an application that resizes for differentscreen resolutions can be quite hard work.

    A good example of this capability is the FlowLayout manager. Ascomponents are added to the container they "flow" out to the edge and thenbegin to wrap around.

    Objective 10.3

    Write code to change the layout scheme associated with an AWTcontainer.

    The Container class contains a method called setLayout(LayoutManager

    mgr);

    Objective 10.4

    User BorderLayout, FlowLayout, and GridLayout to achieve requireddynamic resizing behavior of a component.

    As illustrated in the Applet for Objective 10.2, differentLayoutManagers directly affect the placing and positioning of Componentsin a container. The exam may ask questions that expect you to know what

    happens to the height and width of a button placed at the north of of acontainer when the width of the Container, eg an Applet is resized.

    The exam may give you a bunch of code involving layout managers andthen a series of descriptions of the potential layout of the resulting Gui.Unless you are good with converting code into a visual image thesequestions can be tricky. This is a good time to take advantage of the scrap

    Page 43 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    44/48

    Java Programmer Certification Objectives

    paper you get in the exam room and draw out how the code will affect thefinal layout.

    To understand how the layout managers interact you need to write codethat mixes up the Layout managers and then observe the results. Try creating

    button bars, arrangements of text boxes and labels and watch how they reactwhen the application is re-sized. Remember that only the flow layout(default for an Applet)allows components to be their preferred size, ie for aButton that would be tall enough and wide enough to encompass its text.The way the Grid Layout affects components if you have fewer componentsthan grid cells can seem a little odd.

    11 The java.awt. package Event Handling

    Objective 11.1

    Write a non-abstract class that implements a specified Listenerinterface, given the interface definition.

    The reason this objective specified a non-abstract class is that if youcreate a class that implements a Listener interface, but do not defineevery method in the interface you will get an error indicating that it must

    be abstract because it does not define all methods. One of the simplestinterfaces to use is ActionListener, as it only has one method

    actionPerformed();

    Using the adapter classes is often a more attractive way of dealing withevents because you don't end up with the blank bodies for the interfacesthat have many methods. If this means nothing to you, then note that theobjectives do not specifically ask you to know anything about the Adapterclasses.

    Objective 11.2

    Select methods from the classes in the java.awt.event package thatidentify the affected component, mouse position, nature, and time of theevent.

    This is mainly a dull memory exercise. You can either just try tomemorize it or make it slightly more interesting by writing code that uses

    Page 44 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    45/48

    Java Programmer Certification Objectives

    each and every one of the of the methods. Writing code is probably the bestbet. Event handling was one of the big changes between JDK 1.0 and 1.1.The 1.x method seemed slightly easier to understand, but the new way issaid to be more scalable. If you are writing for the web, bear in mind thatthere are more browsers capable of running Java 1.0 than just about anything(including DHTML), so it really does offer a big cross platform overanything else. Java 1.1 however is much less widespread, but it doesrepresent the one true way.

    There are 11 Event interfaces, each one with one or more methods andan "add" method, to allow you to associate it with an item (such as the

    button in the above example). One of the most useful for applications is theWindowListener as it allows you to create applications that respond toinstructions to shut down.

    It gets a bit dull with applications if you are constantly giving the threefinger salute to shut down Java applications. Note the case of the letters, itis all too easy to AddActionListener() and wonder why you get an errorreferring to an abstract class.

    Listener InterfacesActionListener

    actionPerformed(ActionEvent)addActionListener()

    AdjustmentListener

    adjustmentValueChanged(AdjustmentEvent)addAdjustmentListener()ComponentListener

    componentHidden(ComponentEvent)componentMoved(ComponentEvent)componentResized(ComponentEvent)componentShown(ComponentEvent)

    addComponentListener()ContainerListener

    componentAdded(ContainerEvent)

    componetRemoved(ContainerEvent)addContainerListener()

    FocusListenerfocusGained(FocusEvent)focusLost(FocusEvent)

    addFocusListener()ItemListener

    Page 45 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    46/48

    Java Programmer Certification Objectives

    itemStateChanged(ItemEvent)addItemListener()

    KeyListenerkeyPressed(KeyEvent)

    addKeyListener()MouseListener

    mouseClicked(MouseEvent)mouseEntered(MouseEvent)mouseExited(MouseEvent)mousePressed(MouseEvent)mouseReleased(MouseEvent)

    addMouseListener()MouseMotionListener

    mouseDragged(MouseEvent)

    mouseMoved(MouseEvent)addMouseMotionListener()TextListener

    textValueChanged(TextEvent)addTextListener()

    WindowListenerwindowActivated(WindowEvent)windowClosed(WindowEvent)windowClosing(WindowEvent)windowDeactivated(WindowEvent)

    windowDeiconified(WindowEvent)windowIconified(WindowEvent)|windowOpened(WindowEvent)

    addWindowListener()

    Objective 11.3

    Demonstrate correct uses of the Listener methods in the Component,TextArea, and TextField classes.

    This objective seems to be based around giving a sample component forwhich you must understand how to add and user listener methods. TheTextArea and TextField Components are similar, except that when you hitthe Tab key in a TextField you move to the next component. In a TextAreayou just the cursor moves along one Tab space.

    Objective 11.4

    Page 46 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    47/48

    Java Programmer Certification Objectives

    For any listener in the java.awt.event package, state the argument typeand return type of a specified listener method, given the name of theinterface that declares the method and the name of the method itself.

    Objective 11.2 asked you to learn the methods of the Event Listeners.This objective asks you to learn the argument type and return type of theEvent. The table for 11.2 contains the information for this objective as well.The return type is the easy bit, each lister method has a void return type,iethere is not return value

    The argument types are based on the Listener interface name. Thus allof the MouseLister interface methods take a MouseEvent parameter, theWindowListener interface methods all take a WindowEvent parameter etc,

    etc.

    12: The java.awt.package - Painting

    Objective 12.1

    Identify the sequence of Component methods involved in redrawingareas of an AWT GUI under exposure and programmed redraw conditions.

    If you are just placing components on a Panel or Frame for thepurposes of creating a form like application you ma never need to worryabout the order that the GUI is updated. However if you are creating anapplication that performs functions such as drawing a graph or picture youneed to know howthe screen is graphically updated. This is particularly true if you want tochange what is on the screen.

    This can be illustrated with an applet that doesn't refresh correctly.You need to know that the redrawing of the GUI involves three

    methods in a particular order. These are repaint(); update(); paint();

    repaint(); Repaints the specified rectangle of this component within asettable number of milliseconds. This method causes a call to thiscomponent's update method.

    update(); Updates this component. The AWT calls the update method

    Page 47 of 48 2/18/2012

  • 8/3/2019 Java Test Objectives 2

    48/48

    Java Programmer Certification Objectives

    in response to a call to repaint,update or paint.

    paint(); Paints this component. This method is called when thecontents of the omponent should be

    pinted in response to the component first being shown or damage needingrepair. The clip rectangle in the Graphics parameter will be set to the areawhich needs to be painted.

    Objective 12.2

    Distinguish between methods invoked by the user thread and thosenormally invoked by an AWT thread.

    As mentioned in the previous section the paint() method is called

    whenever the contents of the component get damaged in some way. For thisreason it is a good idea to place all graphics drawing code either in theoverriden paint method or in code called from the paint method. If bycontrast you were to place your drawing code in the update method, thegraphics would be drawn when the applet was first initialised, but would beoverwritten when the applet was re-sized and the paint method was calledfrom the AWT thread.

    Objective 12.3

    Write code to implement the paint() method of a java.awt.Component.

    The signature of the paint method is pubic void paint(Graphics g)