Sunteți pe pagina 1din 48

Java Programmer Certification Objectives

Author Date Version

Narayanan J 2nd Jun 99 1.0

Page 1 of 48

2/18/2012

Java Programmer Certification Objectives

1 Language Fundamentals Objective 1.1 Use standard "javadoc" format documentation to identify and use variables and methods in classes. Employ such documentation to identify variables 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

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 the name 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 param2 argv[0] --> param1 argv[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 explicit assignment 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

Java Programmer Certification Objectives

Determine the value of an element of an array of any base type, when the array has been constructed but no explicit assignment has been made to the element. The value of the elements of an array of any base type will always be initialised to a default value, wherever the array is defined. It does not matter if the array is defined at class or method level, the values will always be set to 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 an identifier cannot contain spaces, and must be letters, digits, underscores or dollar signs. Objective 1.11 Construct literal numeric values using decimal, octal and hexadecimal formats. To represent a number as hexadecimal it is preceded by either : 0X or 0x 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 for a specified character code.
Page 4 of 48 2/18/2012

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 << operators to an int value specified as a bit pattern. Objective 2.2 Determine the result of the + operator applied to a combination of variables or constants of any type. Objective 2.3 Determine the result of applying the == comparison operator to any two objects of any type. Objective 2.4 Determine the result of applying the equals() method to any combination of objects of the classes java.lang.String, java.lang.Boolean, and java.lang.Object The equals method can be considered to perform a deep comparison of the value of an object, wheras the == operator performs a shallow comparison. The equals method compares what an object points to rather than the pointer itself. The operation of the equal method and == operator has some strange side effects when used to compare Strings. This is one occasion when the immutable nature of strings, and the way they are handled by Java can be confusing. There are two ways of creating a String in java. The one way does not use the new operator. Thus normally a String is created String s = new String("Hello"); but a slightly shorter method can be used String s= "GoodBye";
Page 5 of 48 2/18/2012

Java Programmer Certification Objectives

Generally there is little difference between these two ways of creating strings, but the Exam may well ask questions that require you to know the difference. The creation of two strings with the same sequence of letters without the use of 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 the effect 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 "Equal without 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. However because of the way Java conserves resources by re-using identical strings that 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 Java to create separate strings. Because the == operator only compares the address 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 use of == 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 for yourself to see how it works. Try it with various permutations of identical strings created with and without the new operator.
Page 6 of 48 2/18/2012

Java Programmer Certification Objectives

The requirement to understand the use of the equals operator on java.lang.Boolean is a potential gotcha. Boolean is a wrapper object for the boolean primitive. It is an object and using equals on it will test According to the JDK documentation the equals method of the Boolean wrapper class "Returns true if and only the argument is not null and is a Boolean object that contains the same boolean value as this object". eg Boolean 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 are familiar with the if operator in Java you will know you cannot perform the sort 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 be a boolean evaluation, and an Java does not have the C/C++ concept whereby any non null value is considered to be true. However you may come across the following in Java boolean b1; if(b1) { //do something in java } Although this is rather bad programing practice it is syntactically correct, as the parameter for the if operation is a boolean. Objective 2.5 In an expression involving the operators &,|,&&, and || state which operands are evaluated and determine the resulting value of the expression.
Page 7 of 48 2/18/2012

Java Programmer Certification Objectives

Objective 2.6 Determine if an assignment is permitted between any two variables of possibly different types. Objective 2.7 Determine the effect of assignment and modification operations upon variables of any type. 3 : Declarations and Access Control Objective 3.1) Declare variables of type "array of X" for any type X. Identify the legal positions for the "[ ]" part of an array declaration. The declaration of an array does not allocate any storage, it just announces the intention of creating an arryay. As noticed with the signature of the main method arguments, the square backets can come after 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 of array at the point of declaration.. An array declaration can have multiple sets of square brackets. Java does not formally support multi dimensional arrays, however it does support arrays 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 a rectangle. 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 an array. Thus you could set up the sqares on a map with an array of 2
Page 8 of 48 2/18/2012

Java Programmer Certification Objectives

dimensions thus int 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 and specifying its dimensions. Thus for an array of integers with 8 elements you could 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 the second instance, they could just have correctly been placed after the data type as in int[] I=new int[8]; The number in the brackets that specifies the dimension (8 in the previous example), can be a can be a constant, as in this case, or any integer variable. 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 represented in the length field. Thus you can dynamically populate an array with the following code. int myarray[]=new int[10]; for(int j=0; j<myarray.length;j++){ myarray[j]=j; } Thus the array myarray will be easily and pointlessly populated with the numbers zero through to 9. There is no direct equivalent in Java of the redim keyword that redimensions an array. In Java the number of elements is
Page 9 of 48 2/18/2012

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 and initialization format. Instead of looping through an array to perform initialisation, an array can be created and initialised all in one statement. This is particularly suitable 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 is correct. 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, thus you 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++ thus String 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 execute the code a class must be "instantiated", ie a copy created in memory. As a slight contradiction to that last statement, Java does support the static keyword to allow code to run without instantiating an object. This is used in every 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

Java Programmer Certification Objectives

Classes are defined with a access keyword, the class keyword and a name for the class. Thus a class can be defined as public class classname {} This is a legally defined class with no variables, or methods that will compile. The methods and variables are the guts of a java applications. They are the 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 println object that lets you send output to the console. The signature of a method must include a return type, but that type can be 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 but int 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. If you define more than one class in a file with the keword public the compiler will 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, not nested) 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 functionality of an abstract class it must be subclassed. The final modifier could be viewed as the opposite of abstract, in that a final class cannot be subclassed. This prevents other programmers from
Page 11 of 48 2/18/2012

Java Programmer Certification Objectives

creating children of a class. The standard java classes include many examples of final classes. An example is the String class. You cannot add new methods to the string class. You can however create a new class that contains 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 the visibility of variables, ie what code can see their contents. protected A protected variable is visible within a class, and in sub classes, the same package but not elsewhere. The qualification that it is visible from the same package can give more visibility than you might suspect. Any class in the same directory is considered to be in the default package, and thus protected classes will be visible. This means that a protected variable is more visible than a variable defined with no access modifier. A variable defined with no access modifier is said to have default visibility. Default visibility means a variable can be seen within the class, and from elsewhere within 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 way that class level variables are initialised. Static variables are also known as class variables because there can be no more than one copy of each static variable associated with the class. Thus although you might have multiple instances of the class there will only ever be one instance of any static variable. private Private variables are only visible from within the same class they are created. This means they are NOT visible within sub classes Public variables, as you might guess are visible from just about anywhere.

Page 12 of 48

2/18/2012

Java Programmer Certification Objectives

Objective 3.8 State the prototype of the default constructor. List the circumstances which govern creation of a default constructor. This objective is the sort that might catch out an experienced Java programmer. 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 sub class, 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 an invisible 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 with no 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 you have 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 without constructor arguments will now be broken. Java only inserts the default constructor if a class has no other constructors. Of course you can get around this problem by always creating a no args constructor for a class, so adding any other constructors later on will not cause a problem. Objective 3.9 State the consequences, in terms of the results of an assignment to a variable, 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

Java Programmer Certification Objectives

multiple instances of a class are created and assignments are made to a static variable, those assignments will be visible from within other instances of the class. Until Java 1.1 any final variable acted like a C/C++ constant. It had to be initialized at the same time as it was declared and the value could not be modified once it was created. Java 1.1 introduced the idea of blank final variables. This is a variable that is not assigned a value at declaration but once it is assigned a value, such as in a constructor, that value cannot be changed. There is no blank keyword, it is just a final declaration without an assignment, thus. final int iFin; The assignment of a variable is checked at compile time, and an error will be generated if no assignment is made. Objective 3.10 State the effects on scope and accessibility of an instance variable or method of these factors: The calling method is static The calling method is non-static The calling method is in the same class as the target The calling method is in a subclass of the class containing the target The calling method is in a class which is in the same package as the class containing the target No special relationship exists between the class of the caller and the class of the target The 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 or variables in its class Thus the following code will cause an error public class MyClass{
Page 14 of 48 2/18/2012

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 of Error 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 instance variable can be manipulated by a non-static method and the results will be visible 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 the same class. No qualification is needed and no instance of the class need be created. 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 to the 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 referring to 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

Java Programmer Certification Objectives

target Subclasses can refer to instance variables in parent classes as if they were declared in the curent class. It is as if a sub class carries a hidden copy of the variable. No special relationship exists between the class of the caller and the class of the target By no special relationship, I take it to mean that the variable is not in the same package, class, or subclass to the calling method. If the instance method is declared to be public a method in an unconnected class will be able to refer to the variable and manipulate it using the fully qualified name of 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't have an abstract variable). 4 Flow Control and Exception Handling Objective 4.1 Write 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

Java Programmer Certification Objectives

languages. Switch/case statements 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 to represent 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 the argument. A fairly common question seems to about the use of the break statement in the process of falling through a switch statement. Here is an example 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 instructions following a case statement and having come across another case statement the compiler would then finish falling through the switch statement. However for reasons best known to the designers of the language case statements only stop falling through when they come across a break statement. As a result, in the above example both the strings ten and twenty will be sent to the output. Another little peculiarity that can come up on questions is the placing of the default statement. The conventional place for the default statement is
Page 17 of 48 2/18/2012

Java Programmer Certification Objectives

at the end of of case options. Thus normally code will be written as follows int 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 the default 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() and switch(). An if statement can only take a boolean type and a switch can only take 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

Java Programmer Certification Objectives

counter variables. The most common method of looping is to use the for statement. Like C++ and unlike C the variable that controls the looping can be created and initialised 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<5l;K++){ System.out.println("Outer "+K); for(int L=0;L<5;L++) { System.out.println("Inner"+L); } } } } This code will loop 5 times around the inner loop for every time around the outer loop. Objective 4.4 Demonstrate the use of both the labeled and unlabeled versions of the break and continue keywords to modify normal loop behavior. The designers of Java decided that they agreed with programming guru Edsger Dijkstra who wrote a famous article titled "Goto considered harmful". Because indiscriminate use of goto statements can result in hard to maintain spagetti code it has fallen out of use and considered bad programming style. There are situations when it would be useful and to help in those situations Java offers the labeled and unlabeled versions of the break and continue keywords. These allow you to conditionally break out of loops. They do not however, allow you to simply jump to another part of the program. The exam is likely to include questions covering this subject in the form of a set of nested loops. You have to work out what numbers will be printed out before the loops finish due to the action of the break statement. Objective 4.5

Page 19 of 48

2/18/2012

Java Programmer Certification Objectives

Demonstrate the flow of control that occurs in try, catch(), and finally constructions under conditions of normal execution, caught exception and uncaught exception. The try and catch tatements are part of the exception handling built into Java. Neither C/ C++ nor Visual Basic have direct equivalents to Javas built in exceptions. C++ does support exceptions but they are optional, and VB supports On Error/Goto error trapping, which smacks somewhat of a throwback to an earlier less flexible era of BASIC programming. Java exceptions are a built in part of the language. For example if you are 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 piece of code I have used with Borland/Inprise Jbuilder to temporarily halt output to 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 main public 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 programmer must 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 the io methods can causes exceptions and demands exception handling code. This is a little more rigorous than VB or C/C++ which allows you to throw together "quick and dirty" programs that pretend they are in a world where errors do not occur. Remember that the original version of DOS was called QDOS for Quick and Dirty DOS by it's creator and look how long we
Page 20 of 48 2/18/2012

Java Programmer Certification Objectives

have lived with the legacy of that bit of hackery. By the time you have gone to the trouble of putting in a try catch block and blank braces you may as well 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 is under 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 of execution 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 executed is 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 return without running the finally statement. Do not be mislead, the finally clause will almost always run. The try/catch clause must trap errors in the order their natural order of hierarchy. 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 compile try{ 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 method declaration where that method contains code that might throw exeptions.

Page 21 of 48

2/18/2012

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 when declaring a method. Thus in the above example instead of surrounding the calls to dis.read() with the try/catch clause the method declaration includes information on the type of exception that might be thrown. Thus the method called 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 method public 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 supperclass method. An overriding method in a subclass may only throw exceptions declared in the parent class or children of the exceptions declared in the parent class. This is only true for overriding methods not overloading methods. Thus if a method has exactly the same name and arguments it can only throw exceptions declared in the parent class or exceptions that are children of exceptions in the parent declaration. It can however throw fewer or no exceptions. Objective 4.8 Write code to create and throw a specified exception. The keyword to throw an exception unsurprisingly is throw. Thus instead of waiting for the environment to trip an exception code logic can be
Page 22 of 48 2/18/2012

Java Programmer Certification Objectives

written to throw a new Exception. The user created exception is created using the new keyword. Thus if you were checking to see if an object reference 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 specified using the clauses 'is a' and 'has a'. This is a very basic OO question and you will probably get a question on it in the exam. Essentially it seeks to find out if you understand when something is referring the type of class structure that an object belongs to and 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 the distinction can be blurred. If you were a zoologist and knew the correct names for groups of animal types you might say a cat IS A long latin word for 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 or some subclass of that class using the instanceof operator. Note that instanceof is an operator not a method. The syntax is like using 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

Java Programmer Certification Objectives

Overloaded The terms overloaded and overridden are similar enough to give cause for confusion. My way of remembering it is to imagine that something that is overriden has literally been ridden over bya hevy vehicle and no longer exists in its own right. Something that is overloaded is still moving but is loaded down with lots of functionality that is causing it plenty of effort. This is just a little mind trick to stinguish the two, it doesn't have any bearing of the reality of the operations in java. Overloading of methods is a compiler trick to allow you to use the same name to perform different actions depending on parameters. Thus imagine you were designing the interface for a system to run mock java certificate exams (who could this be?). An answer may come in as an integer, a boolean or a text string. You could create a version of the method 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 to be aware of more method names than is strinctly necessary. It would be more useful if you could use a single method name and the compiler would resolve 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 is polymorphism. There are no keywords to remember to override methods, you just create multiple methods with the same name but different numbers and or types. The names of the parameters are not important but the number and types must be different. Thus the following is an example of an overloaded markanswer method

Page 24 of 48

2/18/2012

Java Programmer Certification Objectives

void markanswer(String answer){ } void markanswer(int answer){ } The following is not an example of overloading and will cause a compile 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 will still result in a compile time error, but this time indicating that a method cannot be redefined with a different return type. Overloaded methods do not have any restrictions on what exceptions can be thrown. That is something to worry about with overriding. Overriding Overriding a method means that its entire functionality is being replaced. Overriding is something done in a child class to a method defined in a parent class. To override a method a new method is defined in the child class with exactly the same signature as the one in the parent class. This has the effect of shadowing the method in the parent class and the functionality is no longer directly accessible. Java provides an example of overriding in the case of the equals method that every class inherits from the granddady parent Object. The inherited version of equals simply compares where in memory the instance of 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 by character comparison to see if the two strings are the same. To allow for this the 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

Java Programmer Certification Objectives

State the legal return types for an overloading method given the original method declaration. The return type does not form part of the signature for the purpose of overloading. Thus an overloaded method may return any data type. Objective 5.5 State legal return types for an overriding method given the original method declaration. The return type does matter for the purposes of overriding. An overriden method must have exactly the same return type as the method in the 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 compile time. Objective 5.6 Describe the effect of invoking overridden method in base and derived classes. If a method is overriden (replaced by a method with identical signature), the version in the base class can still be invoked from an instance of the base class. Take the following example class 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

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 be Base 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 have been 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 call the original version of an overriden method by using the super keyword. To use 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 this super.super.super.amethod() //Not legal won't work Objective 5.8 Write constructor bodies using this() and super() to access overloaded or 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 the this object.You can try modifying code to see that prefixing variables with this 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 the following 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 constructor by using this as a constructor thus this(99); public class Try{ static int j=99;
Page 27 of 48 2/18/2012

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 class this(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 somewhat controversial, as you can tell by perusing the java.* newsgroups. Inner classes give the programmer the convenience of nesting related classes within one source file. You cannot be in a position of not having an associated 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 format OuterClassName$InnerClassName An example of a top level inner class (ie not in method scope) is as follows 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 within the enclosing braces of a method. Objective 5.10 Define, in method scope, an anonymous inner class that implements a specified interface.
Page 28 of 48 2/18/2012

Java Programmer Certification Objectives

An anonymous class has no name (surprise surprise). Instead of the syntax 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 that implements 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 named class. Because there is no name for the class it looks a little like an attempt to instantiate an interface, which is not allowed in Java. Objective 5.11 Write code in a non-static method of the outer class to construct an instance of the inner class. There is no catch to this objective, you can construct an instance of an inner class just as you would expect. The following code performs this within a method. public class MyClass1 { public static void main(String argv[]){
Page 29 of 48 2/18/2012

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 no this object exists, or the current this object is not an instance of the outer class. This objective involves using a slightly pecuilar syntax that you will probably rarely use in the real world. For this reason it may be something you will need to rote leaarn and make a point of memorising. In a static method such as main there is no current this object. To allow for creation of an instance of an inner class without reference to the this object you can use the 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 accessible from methods of the inner class. A non static inner class has an implicit reference to the this instance of its enclosing class. Therefore it can access any variable of the enclosing class. An inner class can be marked as static, ie it is not associated with any instance of the outer class, just like a static method is not associated with any particular instance of its enclosing class.
Page 30 of 48 2/18/2012

Java Programmer Certification Objectives

Because it is not associated with any instance of the outer class it cannot access any instance variable of the enclosing class. Of course it can access static variables because there will only ever be one instance of a static variable, no matter how many instance of the outer class is created. An inner class can be defined within a method, ie public void amethod(){ class methclass{} } In this case the enclosing scope is the method. Because variables at method level come into scope as the method executes there is a rule governing how the method level class can access the variables of the enclosing method. A class defined within a method can only access variables at the level of the enclosing method 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 were not 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 class defined within a method has access to variables defined at the level of the enclosing class. 6: Garbage Collection Objective6.1 Distinguish 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

Java Programmer Certification Objectives

had to familiarise yourself with the details of garbage collection. One of the great touted beauties of the language is that you don't have to worry about garbage collection. Unlike C/C++ Java automatically frees up unused references. You don't have to go through the pain of searching for allocations that are never freed and you don't need to know how to alloc a sizeof a data type according to the platform. So why would you want to know 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 in extreme circumstances. If you write code that create very large numbers of objects or variables it can be useful to know when references are released. If you read the newsgroups you will see people reporting occasions of certain Java implementations exhausting memory resources and falling over. This was not in the brochure from Sun when the launched Java. In keeping with the philosophy of automatic garbage collection you can suggest or encourage the JVM to perform garbage collection but you cant 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 is that Java internal resources do not need to be cleaned up during finalisation because the garbage collector looks after memory allocation. However if you have external resources such as file information finalisation can be used to free external resources. Garbage collection is a tricky one to write exercises with or practice with as there is no obvious way to get code to indicate when it is available for 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 for garbage collection. You can suggest garbage collection with System.gc(), but this does not guarantee when it will happen

Page 32 of 48

2/18/2012

Java Programmer Certification Objectives

Objective 6.2 Identify the earliest point in a method at which the object referred to by a local variable is definitely eligible to be garbage collected, in the absence of compiler optimization. Local variables in methods go out of scope when the method exits. At this point the methods are eligible for garbage collection. Each time the method 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 the Runnable interface and the Thread class. Threads are lightweight processes that appear to run in parallel with your 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 portion of the program. It would also be useful if the main program would respond if the printing thread encountered a problem. A common example used to illustrate threads is to create a gui application that launches a bouncing ball every time a button is clicked. Unlike most language threading is embedded at the heart of the Java language, much of it at the level of the ultimate ancestor class called Object. Of the two methods of creating a new thread the use of runnable is probably more common, but you must know about both. Here is an example of 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 must include a run method if you implement runnable. Not including a run method
Page 33 of 48 2/18/2012

Java Programmer Certification Objectives

will cause a compile time error. The other method for creating a thread is to create a class that is descended from Thread. This is easy to do but it means you cannot inherit from any other class, as java only supports single inheritance. Objective 7.2 State the requirements for a concrete class that is declared to implement the java.lang.Runnable interface. Any class that is implements an interface must create a method to match all of the methods in the interface. The methods need not do anything sensible, 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 this in any class that implements the runnable interface. To do anything useful when you create a thread of execution from a class you would, of course need 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 the thread class. The runnable interface does not contain a start method, so to get at this and the other useful methods for threads (sleep, suspend etc etc), you pass your class with the runnable interface as the constructor to an instance of the Thread class. Thus to cause the thread to execute from a class that implements runnable you would call the following

Page 34 of 48

2/18/2012

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 is the 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 call the start method. The drawback of sub classing the Thread class is that due to only supporting single inheritance you cannot inherit the functionality of any other class. Objective 7.5 State and recognize conditions that might prevent a thread from executing. The expression "prevent a thread from executing" is slightly ambiguous, does it mean a thread that has been deliberately paused, or does it also include threads that have died?. A thread that is prevented from executing is said to be blocked. a thread may be blocked because 1) it has been put to sleep for a set amount of time 2) It is suspended with a call to the suspend() method and will be blocked until it gets sent the resume message 3) 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 complete 5) The thread is calling another synchronized method that is not available. For the purposes of the exam sleep(), suspend and wait/notify are probably 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 of execution to obtain an object lock prior to proceeding. The synchronized keyword can be used to mark a statement or block of code so that only one thread may execute an instance of the code at a time.
Page 35 of 48 2/18/2012

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 method thus synchronized void amethod() { /* method body */} For a block of code the synchronized keyword comes before opening and closing brackets thus. synchronized (ObjectReference) { /* Block body */ } The value in parentheses indicates the object or class whose monitor the code needs to obtain. When a synchronized block is executed, its object is locked and it cannot 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 placing the keyword synchronized before a block of code. It must be used in conjunction 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 an object 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 to obtain the lock and continue some processing. The wait method is meaningless without the use of notify or notifyAll which allows code that is waiting to be notified that it can wake up and continue executing. Objective 7.8

Page 36 of 48

2/18/2012

Java Programmer Certification Objectives

Define the behavior of a thread which invokes the notify() or notifyAll() methods of an object and the effect of the method on the object lock 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 objects monitor". Unsurprisingly notifyAll "wakes up all threads that are waiting on this 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 must therefore be running. Once woken up, these threads are in the ready state. If more 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 scheduling implementation for threading was ffectively left vendor implemented. This means that you cannot exactly predict how threads will react between one vendors version of java and another. You may even find differences between the 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 work on different systems is not predictable. The use of notify and notifyAll is tied up in the following objective which shows it in use along with wait. Objective 7.9 Define the interaction between threads executing the wait(), notify(), or notifyAll() methods, and the object lock flag. The wait/notify(All) protocol is useful where more than one program needs to access data. If the update of information is not carefully controlled the data may become inconsistent. To allow access to the data to be synchronized every object in each class has a monitor. Only one thread at a time can one an individual monitor.

Page 37 of 48

2/18/2012

Java Programmer Certification Objectives

Examples of threads often have apparently endless loops such as //producing code while(true){ try{ wait(); }catch (InterruptedException e) {} } //some producing action goes here notifyAll(); 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 up the lock on the object and wait until the notify or notifyAll method tells you to wake up. This sort of looping code will be matched with a similar type of consuming code. In the Roberts and Heller chapter on threads they give two top key pieces of advice Always check the monitors state in a while loop rather than an if statement after changing the monitors state, call notifyAll() rather than notify(); The reason for the use of notifyAll is because notify does not allow you 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.Math class 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. I personally had to take a second look at the use of abs and you might get a a question that asks what the effect of ceil or floor on a negative number. The random function returns Objective 8.2
Page 38 of 48 2/18/2012

Java Programmer Certification Objectives

Write code to demonstrate the use of the following methods of the java.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 on them. Thus you cannot use the mathemtatical operators to multiply, subtract or perform logical operations on Strings. You can however use the + sign to concatenate two strings. Thus the following code will output the string Hello There String 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 Strings was too useful to leave out. If you are from a VB background, remember that 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 once created 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

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 and the reference s1 now points to this new string. The objective asks you to recognise the implications of the immutability of strings, and the main one seems to be that if you want to chop and change the contents of "strings" the StringBuffer class comes with more 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 a specified number of columns. Objective 9.3 Construct a java.awt.TextArea or java.awt.TextField that prefers to display a specified number of columns. Objective 9.4 State the significance of a "column" where one of the text components is 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

Java Programmer Certification Objectives

columns, the pitch of the current font will influence how many actual text characters will appear. Thus if you have a proportional font that contains a string with many "wide" wide characters in it such as W, it will be able to display fewer characters than if it was set to a monospaced, typwriter style font 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 draw the image with the following code. Graphics g = MyImage.getGraphics(); Objective 9.7 Distinguish between situations that require the use of an Image object from those that require the use of a Graphics object. You can get an idea of the situations that require an image or graphic if you use the analogy of a Graphic as a photographic film and the Image as the idea, or framing of a photo to be taken on the film. You almost always use a Graphic with an Image but you may often use a Graphic without an image. The image class has methods for scaling and filtering a picture but not for drawing new lines or areas on a picture. The image file does not have a constructor but gets populated with its picture by using the getImage() method of Applet or , Toolkit in an application, or the createImage() method of Component or Toolkit. A graphics object is needed in order to display an image object. The graphics method drawimage is used to actually draw the image on screen. It has the signature public abstract boolean drawImage (Image image, int x, int y, ImageObserver observer)
Page 41 of 48 2/18/2012

Java Programmer Certification Objectives

Situations where you might use a Graphics object without an Image are 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 Graphics and Image object together, was if you were creating a program to load a series 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 in the java.awt and java.awt packages are valid arguments to these methods. Use of the add method is fairly straightforward. Typically the add method might be used as Button 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 to use the 1.1 method, add(Component, Object), in place of this method. //EndQuote It is interesting to speculate why a strong recommendation is given rather 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, ie Buttons, TextFields, Labels, Lists etc. Objective 10.2
Page 42 of 48 2/18/2012

Java Programmer Certification Objectives

Distinguish between AWT classes which are directly responsible for determining component layout and those which are responsible for implementing that layout. This objective seems to be strangely worded, but it appears to ask you to understand layout managers interact with components and containers to determine the eventual appearance of an application or applet. Because Java lays great emphasis on cross platform capability, programs should present a similar appearance all platforms. This is unlike systems such as VB or Delphi where the programmer can specify the position of components to the pixel level. Indeed, in VB creating an application that resizes for different screen resolutions can be quite hard work. A good example of this capability is the FlowLayout manager. As components are added to the container they "flow" out to the edge and then begin to wrap around. Objective 10.3 Write code to change the layout scheme associated with an AWT container. The Container class contains a method called setLayout(LayoutManager mgr); Objective 10.4 User BorderLayout, FlowLayout, and GridLayout to achieve required dynamic resizing behavior of a component. As illustrated in the Applet for Objective 10.2, different LayoutManagers directly affect the placing and positioning of Components in 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 a container when the width of the Container, eg an Applet is resized. The exam may give you a bunch of code involving layout managers and then a series of descriptions of the potential layout of the resulting Gui. Unless you are good with converting code into a visual image these questions can be tricky. This is a good time to take advantage of the scrap
Page 43 of 48 2/18/2012

Java Programmer Certification Objectives

paper you get in the exam room and draw out how the code will affect the final layout. To understand how the layout managers interact you need to write code that mixes up the Layout managers and then observe the results. Try creating button bars, arrangements of text boxes and labels and watch how they react when the application is re-sized. Remember that only the flow layout (default for an Applet)allows components to be their preferred size, ie for a Button that would be tall enough and wide enough to encompass its text. The way the Grid Layout affects components if you have fewer components than 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 Listener interface, given the interface definition. The reason this objective specified a non-abstract class is that if you create a class that implements a Listener interface, but do not define every 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 simplest interfaces to use is ActionListener, as it only has one method actionPerformed(); Using the adapter classes is often a more attractive way of dealing with events because you don't end up with the blank bodies for the interfaces that have many methods. If this means nothing to you, then note that the objectives do not specifically ask you to know anything about the Adapter classes. Objective 11.2 Select methods from the classes in the java.awt.event package that identify the affected component, mouse position, nature, and time of the event. This is mainly a dull memory exercise. You can either just try to memorize it or make it slightly more interesting by writing code that uses
Page 44 of 48 2/18/2012

Java Programmer Certification Objectives

each and every one of the of the methods. Writing code is probably the best bet. 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 is said to be more scalable. If you are writing for the web, bear in mind that there are more browsers capable of running Java 1.0 than just about anything (including DHTML), so it really does offer a big cross platform over anything else. Java 1.1 however is much less widespread, but it does represent the one true way. There are 11 Event interfaces, each one with one or more methods and an "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 the WindowListener as it allows you to create applications that respond to instructions to shut down. It gets a bit dull with applications if you are constantly giving the three finger salute to shut down Java applications. Note the case of the letters, it is all too easy to AddActionListener() and wonder why you get an error referring to an abstract class. Listener Interfaces ActionListener actionPerformed(ActionEvent) addActionListener() AdjustmentListener adjustmentValueChanged(AdjustmentEvent) addAdjustmentListener() ComponentListener componentHidden(ComponentEvent) componentMoved(ComponentEvent) componentResized(ComponentEvent) componentShown(ComponentEvent) addComponentListener() ContainerListener componentAdded(ContainerEvent) componetRemoved(ContainerEvent) addContainerListener() FocusListener focusGained(FocusEvent) focusLost(FocusEvent) addFocusListener() ItemListener
Page 45 of 48 2/18/2012

Java Programmer Certification Objectives

itemStateChanged(ItemEvent) addItemListener() KeyListener keyPressed(KeyEvent) addKeyListener() MouseListener mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) addMouseListener() MouseMotionListener mouseDragged(MouseEvent) mouseMoved(MouseEvent) addMouseMotionListener() TextListener textValueChanged(TextEvent) addTextListener() WindowListener windowActivated(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 for which you must understand how to add and user listener methods. The TextArea and TextField Components are similar, except that when you hit the Tab key in a TextField you move to the next component. In a TextArea you just the cursor moves along one Tab space. Objective 11.4
Page 46 of 48 2/18/2012

Java Programmer Certification Objectives

For any listener in the java.awt.event package, state the argument type and return type of a specified listener method, given the name of the interface 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 the Event. 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,ie there is not return value The argument types are based on the Listener interface name. Thus all of the MouseLister interface methods take a MouseEvent parameter, the WindowListener 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 redrawing areas of an AWT GUI under exposure and programmed redraw conditions. If you are just placing components on a Panel or Frame for the purposes of creating a form like application you ma never need to worry about the order that the GUI is updated. However if you are creating an application that performs functions such as drawing a graph or picture you need to know how the screen is graphically updated. This is particularly true if you want to change 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 a settable number of milliseconds. This method causes a call to this component's update method. update(); Updates this component. The AWT calls the update method
Page 47 of 48 2/18/2012

Java Programmer Certification Objectives

in response to a call to repaint,update or paint. paint(); Paints this component. This method is called when the contents of the omponent should be pinted in response to the component first being shown or damage needing repair. The clip rectangle in the Graphics parameter will be set to the area which needs to be painted. Objective 12.2 Distinguish between methods invoked by the user thread and those normally 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 this reason it is a good idea to place all graphics drawing code either in the overriden paint method or in code called from the paint method. If by contrast you were to place your drawing code in the update method, the graphics would be drawn when the applet was first initialised, but would be overwritten when the applet was re-sized and the paint method was called from 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)

Page 48 of 48

2/18/2012

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