Sei sulla pagina 1di 23

1

SCJP for Java 2 Platform 1.4 Preparation Notes


Issue: 2 Date: April 17, 2003 Author: Nishant Krishna

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

Document Revision History Issue 1 2 Changes Creation of initial document template. Updated Objectives and Resources sections. Updated SCJP tips section. Date March 28, 2003 April 13, 2003 April 17, 2003

References 1. 2. 3. 4. Java 2 Exam Notes, Phillip Heller Complete Java 2 Certification Study Guide, Robert, Heller & Ernest Java Programmers Reference, Grant Palmer Java(TM) 2 SDK, Standard Edition Documentation http://sun.java.com http://www.javaranch.com http://developer.java.sun.com/developer/onlineTraining/

5. 6. 7.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

Table of Contents
Table of Contents....................................................................................................................3 SCJP 1.4 Objectives.................................................................................................................6
SUN CERTIFIED PROGRAMMER FOR THE JAVA 2 PLATFORM 1.4........................................6 SUN CERTIFIED PROGRAMMER FOR JAVA[tm] 2 PLATFORM 1.4 ........................................6

SCJP Tips...............................................................................................................................10 SECTION 1: DECLARATIONS AND ACCESS CONTROL..........................................................10


Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization. .............................................10 Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract, etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. .......................................................................................................10 For a given class, determine if a default constructor will be created and if so state the prototype of that constructor. ....................................................................................11 Identify legal return types for any method given the declarations of all related methods in this or parent classes. ...............................................................................................11

SECTION 2: FLOW CONTROL, ASSERTIONS, AND EXCEPTION HANDLING............................11


Write code using if and switch statements and identify legal argument types for these statements. .............................................................................................................11 Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution. ...............................................................................................................12 Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions. ..................12 Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination). ................................12 Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions. ................................................................................12 Identify correct statements about the assertion mechanism. ..........................................13

SECTION 3: GARBAGE COLLECTION...................................................................................13


State the behavior that is guaranteed by the garbage collection system. .........................13 Write code that explicitly makes objects eligible for garbage collection. ...........................13 Recognize the point in a piece of source code at which an object becomes eligible for garbage collection. ................................................................................................................13

SECTION 4: LANGUAGE FUNDAMENTALS...........................................................................14


Identify correctly constructed package declarations, import statements, class declarations (of all forms including inner classes) interface declarations, method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers. ...............................................................................................................................14

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

4
Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specified interface in the question. .....................................14 State the correspondence between index values in the argument array passed to a main method and command line arguments. ........................................................................14 Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinctions between keywords and manifest constants. .......................15 State the effect of using a variable or array element of any kind when no explicit assignment has been made to it. .................................................................................................15 State the range of all primitive formats, data types and declare literal values for String and all primitive types using all permitted formats bases and representations. ........................15

SECTION 5: OPERATORS AND ASSIGNMENTS.....................................................................16


Determine the result of applying any operator (including assignment operators and instance of) to operands of any type class scope or accessibility or any combination of these. .........16 Determine the result of applying the boolean equals (Object) method to objects of any combination of the classes java.lang.String, java.lang.Boolean and java.lang.Object. ........16 In an expression involving the operators &, |, &&, || and variables of known values state which operands are evaluated and the value of the expression. ......................................17 Determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying operations in that method. ...........................17

SECTION 6: OVERLOADING, OVERRIDING, RUNTIME TYPE AND OBJECT ORIENTATION........17


State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships "is a" and "has a". ..............................17 Write code to invoke overridden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these methods. ....................................17 Write code to construct instances of any concrete class including normal top level classes and nested classes. ........................................................................................................18

SECTION 7: THREADS........................................................................................................18
Write code to define, instantiate and start new threads using both java.lang.Thread and java.lang.Runnable. ..................................................................................................18 Recognize conditions that might prevent a thread from executing. ..................................19 Write code using synchronized wait, notify and notifyAll to protect against concurrent access problems and to communicate between threads. ..........................................................19 Define the interaction among threads and object locks when executing synchronized wait, notify or notifyAll. .....................................................................................................19

SECTION 8: FUNDAMENTAL CLASSES IN THE JAVA.LANG PACKAGE....................................20


Write code using the following methods of the java.lang.Math class: abs, ceil, floor, max, min, random, round, sin, cos, tan, sqrt. ......................................................................20 Describe the significance of the immutability of String objects. .......................................20 Describe the significance of wrapper classes, including making appropriate selections in the wrapper classes to suit specified behavior requirements, stating the result of executing a fragment of code that includes an instance of one of the wrapper classes, and writing code using the following methods of the wrapper classes (e.g., Integer, Double, etc.): doubleValue floatValue intValue longValue

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

5
parseXxx getXxx toString toHexString .............................................................................................................21

SECTION 9: THE COLLECTIONS FRAMEWORK.....................................................................21


Make appropriate selection of collection classes/interfaces to suit specified behavior requirements. ..........................................................................................................21 Distinguish between correct and incorrect implementations of hashCode methods. ............22

Resources.............................................................................................................................23 Web Sites..........................................................................................................................23 Books................................................................................................................................23

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

SCJP 1.4 Objectives


SUN CERTIFIED PROGRAMMER FOR THE JAVA 2 PLATFORM 1.4
Purchase: Sun training Available at: Authorized Prometric testing centers Exam number: CX-310-035 Prerequisites: None Exam type: Multiple choice and short answer Number of questions: 61 Pass score: 52% (32 of 61 questions) Time limit: 120 minutes Cost: US$150, or as priced in the country where the exam is taken

SUN CERTIFIED PROGRAMMER FOR JAVA[tm] 2 PLATFORM 1.4


SECTION 1: DECLARATIONS AND ACCESS CONTROL Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization. Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract, etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. For a given class, determine if a default constructor will be created and if so state the prototype of that constructor. Identify legal return types for any method given the declarations of all related methods in this or parent classes. SECTION 2: FLOW CONTROL, ASSERTIONS, AND EXCEPTION HANDLING Write code using if and switch statements and identify legal argument types for these statements. Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution. Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions. Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination). Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions. Identify correct statements about the assertion mechanism. SECTION 3: GARBAGE COLLECTION 9/7/2012 Wipro Technologies Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

7
State the behavior that is guaranteed by the garbage collection system. Write code that explicitly makes objects eligible for garbage collection. Recognize the point in a piece of source code at which an object becomes eligible for garbage collection. SECTION 4: LANGUAGE FUNDAMENTALS Identify correctly constructed package declarations, import statements, class declarations (of all forms including inner classes) interface declarations, method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers. Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specified interface in the question. State the correspondence between index values in the argument array passed to a main method and command line arguments. Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinctions between keywords and manifest constants. State the effect of using a variable or array element of any kind when no explicit assignment has been made to it. State the range of all primitive formats, data types and declare literal values for String and all primitive types using all permitted formats bases and representations. SECTION 5: OPERATORS AND ASSIGNMENTS Determine the result of applying any operator (including assignment operators and instance of) to operands of any type class scope or accessibility or any combination of these. Determine the result of applying the boolean equals (Object) method to objects of any combination of the classes java.lang.String, java.lang.Boolean and java.lang.Object. In an expression involving the operators &, |, &&, || and variables of known values state which operands are evaluated and the value of the expression. Determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying operations in that method. SECTION 6: OVERLOADING, OVERRIDING, RUNTIME TYPE AND OBJECT ORIENTATION State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships "is a" and "has a". Write code to invoke overridden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these methods. Write code to construct instances of any concrete class including normal top level classes and nested classes. SECTION 7: THREADS 1. Write code to define, instantiate and start new threads using both java.lang.Thread and java.lang.Runnable. 2. Recognize conditions that might prevent a thread from executing. 3. Write code using synchronized wait, notify and notifyAll to protect against concurrent access problems and to communicate between threads. 4. Define the interaction among threads and object locks when executing synchronized wait, notify or notifyAll. 9/7/2012 Wipro Technologies Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

8
SECTION 8: FUNDAMENTAL CLASSES IN THE JAVA.LANG PACKAGE Write code using the following methods of the java.lang.Math class: abs, ceil, floor, max, min, random, round, sin, cos, tan, sqrt. Describe the significance of the immutability of String objects. Describe the significance of wrapper classes, including making appropriate selections in the wrapper classes to suit specified behavior requirements, stating the result of executing a fragment of code that includes an instance of one of the wrapper classes, and writing code using the following methods of the wrapper classes (e.g., Integer, Double, etc.): a. doubleValue b. floatValue c. intValue d. longValue e. parseXxx f. getXxx g. toString h. toHexString

SECTION 9: THE COLLECTIONS FRAMEWORK Make appropriate selection of collection classes/interfaces to suit specified behavior requirements. Distinguish between correct and incorrect implementations of hashcode methods.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

10

SCJP Tips
SECTION 1: DECLARATIONS AND ACCESS CONTROL
Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms both for declaration and for initialization.

1. Following are valid ways to define a double dimension arrays:


int [][] doubleArray = new int [10][10]; int doubleArray[][] = new int [10][10]; int [] doubleArray[] = new int[10][10]; 2. A single dimension array can be defined in the following way also: int singleArray[] = new int[] {10, 20, 30, 40, 50}; 3. Arrays are always initialized to the default value of the type it contains, be it local array or otherwise. 4. A value for first index has to be provided by the user, otherwise the code wont compile.

Declare classes, nested classes, methods, instance variables, static variables and automatic (method local) variables making appropriate use of all permitted modifiers (such as public, final, static, abstract, etc.). State the significance of each of these modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. private, protected, public 1. Private variables/methods have class level access. 2. Private methods are not visible in the subclass. It means that a method with the same name in the subclass is an altogether different method, instead of being an override. 3. Protected variables/methods can be accessed in the same class, the same package and in the sub-classes. 4. Public variables/methods are visible to the world. 5. Variables/methods having no explicit access modifier associated with them have default access, i.e., they can be access in the current class and in the current package. static 1. 2. 3. 4. 5. A static method cannot be overridden by a non-static method. A static method can be overridden by a static method. A static method can be overloaded with a non-static method. A static method can be inherited. A static variable can be overridden by a non-static variable in the child class.

abstract 1. Classes and methods can be abstract. 2. If a class is abstract, no instance of that class can be created. 3. If a method is abstract, the subclass should give the implementation for that method. 4. Even if a single method of a class is declared as abstract, the class itself has to be declared as abstract. On the other hand, a class declared as abstract may not has any abstract method. final 9/7/2012 Wipro Technologies Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

11 1. Classes, variables and methods can be declared final. 2. Class declared as final cant be sub-classed. 3. If variables declared as final, the value they contain cant be changed.
4. Method declared as final cant be overridden. 5. If an object is declared as final, the reference it stores cant be changed, but the content of the object it is pointing to, can be changed. transient 1. 2. native 1. Native applies only to methods. 2. A native method calls code in a library specific to the underlying hardware. 3. It's like an abstract method in the sense that the implementation exists somewhere other than the class in which the method is declared. volatile 1. Volatile applies only to class variables.

The transient modifier applies only to class variables. During serialization, an object's transient variables are not serialized.

For a given class, determine if a default constructor will be created and if so state the prototype of that constructor. 1. 2. 3. 4. A default constructor is a constructor with empty argument list. A default constructor is automatically generated by the compiler if the class does not have one. If an explicit constructor is there in the class, the default constructor is not generated. Access mode of the generated constructor is public for public classes, and default for classes with any other access mode. 5. If a subclass has a default constructor and a super class has an explicit constructor, the code will not compile due to the automatic insertion of super() in the generated constructor by the compiler.

Identify legal return types for any method given the declarations of all related methods in this or parent classes. 1. It is legal for overloaded methods to have same or different return types, as far as their argument list is different. 2. Overridden methods should have the same return type in the subclass. If the name and argument list are the same but the return type is different here, the compilation will fail.

SECTION 2: FLOW CONTROL, ASSERTIONS, AND EXCEPTION HANDLING


Write code using if and switch statements and identify legal argument types for these statements. 1. The argument of an if statement must be of boolean type. Using anything other than boolean will not compile.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

12
2. Only those primitive data types can be used in switch statement, which can be automatically converted to int, viz., byte, short, char, int.

Write code using all forms of loops including labeled and unlabeled, use of break and continue, and state the values taken by loop counter variables during and after loop execution. Please refer to books in Resources section.

Write code that makes proper use of exceptions and exception handling clauses (try, catch, finally) and declares methods and overriding methods that throw exceptions. 1. Exceptions are abnormal circumstances in the program, which cant be handled by normal program flow. 2. Exceptions which are not subclasses of RuntimeExceptions are called checked exceptions. 3. A finally block is always executed irrespective of exception is caught of not. The only exception to this rule is when the current thread dies before the finally block, e.g. A call to System.exit(). 4. Overriding method should throw only the exception thrown by the overridden method or the subclass of the exception. They should throw no new checked exceptions. 5. There can be more than one catch block; the exception caught in them should be specific to generic from top to bottom. If a generic exception class (e.g., Exception, Throwable) is used to catch the exception before a specific class, all the exception can be caught by them, and catch blocks below them become unreachable. Hence, the code will not compile. 6. try-catch-finally blocks can be nested.

Recognize the effect of an exception arising at a specified point in a code fragment. Note: The exception may be a runtime exception, a checked exception, or an error (the code may include try, catch, or finally clauses in any legitimate combination).

1. When an exception occurs in the program, if no care has been taken to deal with the exception, the
execution of the program jumps to the end of the current method and the execution goes to caller of that method and again the execution jumps to the end of the caller method. This goes on until execution of the program reaches the top of the execution stack, where the thread dies. The side effect is seen as a stack trace of the whole execution stack. 2. If explicit exception handling has been done, the thrown exception is caught in the catch block, where it can be handled properly. After that the finally block is executed, if one exists, and the execution continues after the end of the try-catch-finally block.

Write code that makes proper use of assertions, and distinguish appropriate from inappropriate uses of assertions. 1. An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. 2. Each assertion contains a boolean expression that you believe will be true when the assertion executes. If it is not true, the system will throw an error. 3. By verifying that the boolean expression is indeed true, the assertion confirms your assumptions about the behavior of your program, increasing your confidence that the program is free of errors.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

13 4. The assertion statement has two forms:


assert Expression1; assert Expression1 : Expression2; First form evaluates the boolean expression Expression1 and if it is false, throws an AssertionError with no detail message. The second form is used to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message. 5. Assertions should not be used for argument checking in public methods. 6. Assertions should not be used to do any work that your application requires for correct operation. 7. For bringing the assertion mechanism in effect, the class should be compiled with javac -source 1.4 <Class>, and then while executing the class, -ea (enable assertion) switch of java should be used

Identify correct statements about the assertion mechanism. 1. An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. 2. Once an assertion is failed, there is no way to recover from the failure. The program is terminated. 3. Assertions are commonly used to check preconditions, postconditions and class invariants. 4. A precondition is a constraint that must be true when a method is invoked. 5. A postcondition is a constraint that must be true after a method completes successfully. 6. A class invariant is a constraint that tells what must be true about each instance of a class. 7. It is valid to explicitly throw AssertionError by any subclass, or mention the same in the throws clause, as AssertionError extends from Error, not Exception.

SECTION 3: GARBAGE COLLECTION


State the behavior that is guaranteed by the garbage collection system.

1. Garbage collector is a low priority thread which runs in background when the system goes out of
memory or the CPU load is low, and reclaims the memory taken by unused objects. 2. Calling System.gc() and Runtime.gc() only suggest garbage collection to JVM, but do not guarantee that garbage collection will be run immediately. 3. It is not promised that as soon as there are no references to an object, the garbage collector will be run. 4. Till an object is accessible to any live thread, that object will not be garbage collected.

Write code that explicitly makes objects eligible for garbage collection. 1. For explicitly making objects eligible for garbage collection, assign null to them, when you are done with them. 2. Using finalize() method is also a good idea. It is guaranteed that the finalize() method will be called, when the object is about to be garbage collected.

Recognize the point in a piece of source code at which an object becomes eligible for garbage collection. 9/7/2012 Wipro Technologies Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

14
An object will become eligible for garbage collection only if is it not accessible to any live thread. For this all the references to the object should be null. Please refer to books in Resources section.

SECTION 4: LANGUAGE FUNDAMENTALS


Identify correctly constructed package declarations, import statements, class declarations (of all forms including inner classes) interface declarations, method declarations (including the main method that is used to start execution of a class), variable declarations, and identifiers. Identifiers 1. Identifiers can be of unlimited length. 2. They can begin with a _ (Underscore), a $ or a character. 3. Since all the Unicode characters are valid characters in Java, the identifier can contain any character from the entire Unicode character set. \u000A causes problem while compilation, as it expands to a new line character. Interfaces 1. All the attributes are public, static and final by default. 2. All the methods are public and abstract by default. 3. An interface can extend one or more interface. 4. An interface is loaded in memory only when it is needed for the first time Constructors 1. Constructors are not inherited. 2. The default constructor is lost when a user-defined constructor (with arguments or without arguments) is added to the class. 3. Call to this() and super() always must be first statement in constructor.

Identify classes that correctly implement an interface where that interface is either java.lang.Runnable or a fully specified interface in the question. 1. A class which implements an interface needs to provide the implementation of all the methods in that interface. 2. If implementation for all the methods declared in the interface are not provided, the class itself should be declared as abstract, otherwise the class will not compile. 3. A class can implement more than one interface. 4. Implementing java.lang.Runnable interface does not mean that the class has to implement a run() method. 5. If a class implements two interface and both the interfaces have identical method declaration, it is totally valid. 6. If a class implements two interface and both the interfaces have identical method names and argument lists but return type different, the code will not compile.

State the correspondence between index values in the argument array passed to a main method and command line arguments. 1. The main method is declared as public static void main (String[] args) {}. The place for public and static can be interchanged, but void has to be there before the name of the method.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

15 2. A class can have a declaration which does not match the required declaration, but that main 3.
method will not be called when the class is invoked. When command line arguments are supplied to main(), java and the name of the program are not part of the argument list, e.g., when myClass is passed an argument as java myClass red green blue, red will have an index of 0, green will have an index of 1 and blue will have an index of 2. This is different with C and C++.

Identify all Java programming language keywords. Note: There will not be any questions regarding esoteric distinctions between keywords and manifest constants. Following are 52 valid keywords in Java 1.4. You just be able to distinguish a non-keyword with a key-word. Abstract Assert Boolean Break Byte Case Catch char class const continue default Do double Else Extends False Final Finally Float For goto if implements import instanceof int interface Long native new null package private protected Public Return Short Static strictfp Super switch synchronized this throw throws transient true Try void volatile while

State the effect of using a variable or array element of any kind when no explicit assignment has been made to it. When no explicit assignment is made to a variable or array element of any kind, following are the default value assigned to the variables by compiler: boolean false char \u0000 byte 0 short 0 int 0 long 0 float 0.0 double 0.0 All objects null

State the range of all primitive formats, data types and declare literal values for String and all primitive types using all permitted formats bases and representations. Primitive Data Types boolean char byte short int long float double 9/7/2012 Wipro Technologies

1 bit 16 bits 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

16

1. All the integer data types are signed data types, and are represented in 2s complement form. There is nothing called signed or unsigned char in Java. 2. Floating point numbers are double by default. 3. All the arithmetic operations result in at least an int. Also anything less than an int is promoted to int before performing an arithmetic operation. 4. Automatic casting: byte -> short (and char) -> int -> long -> float -> double Any assignment in the reverse direction requires an explicit cast. Here even a byte (also short, int etc.) cant be assigned to a char without explicit cast, as there can be a possible loss of precision, as char data type is not signed. 5. Though the length of long is 64 bits and the length of float is 32 bits, assigning a long to a float will not give any compiler error due to internal representation of float.

SECTION 5: OPERATORS AND ASSIGNMENTS


Determine the result of applying any operator (including assignment operators and instance of) to operands of any type class scope or accessibility or any combination of these. Operators and Expressions 1. % operators are generally used with integers but they can be used with floating point numbers also. 2. % and / never produce an ArithmeticException when used with floating point numbers. e.g. 2.3f / 0 will not produce any exception. 3. All the arithmetic operators produce results of int, long, float or double type only. All the other results should be explicitly typecasted before assignment if the variable in the left side is of smaller size. e. g. short a = 10 * 5; should be written as short a = (short) 10 * 5; 4. The ^ (exclusive OR or XOR) operator returns a value of true if only one of the operands is true. If both are true or both are false, it returns false. 5. Bytes, Shorts and Chars are automatically promoted to int when used with unary operators. 6. Using >> and << does not change the left most bit, i.e., the sign bit. The >>> (right shift with zero fill) changes the initial -ve sign (i.e., 1 in the leftmost bit) to +ve. 7. Using >> by 1 is equal to dividing the number by 2, and using << by 1 is equal to multiplying the number by 2. 8. Widening conversions are done automatically by the compiler. Narrowing conversions are not permitted, so explicit typecasts are needed. 9. Assignments are from right to left. 10. Just like multiple assignment, multiple increment and assignments are also possible. e.g. a += b += c; is valid Determine the result of applying the boolean equals (Object) method to objects of any combination of the classes java.lang.String, java.lang.Boolean and java.lang.Object. 1. Boolean b1 = new Boolean("true"); Boolean b2 = new Boolean("true"); Here b1 and b2 will point to different memory locations as they are different objects altogether, so they will not be equal (==) 2. Boolean b1 = new Boolean("TRUE"); Boolean b2 = new Boolean("true"); Here both will be equal (==), as their content is the same. As a wrapper class, Boolean is not case sensitive with the value passed to it as the argument. 9/7/2012 Wipro Technologies Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

17

3. Boolean b1 = new Boolean("true"); Boolean b2 = new Boolean("another string"); Anything apart from true/TRUE, false/FALSE are taken as false in the Boolean wrapper class. So, printing the second variable will simply print false.

In an expression involving the operators &, |, &&, || and variables of known values state which operands are evaluated and the value of the expression.

1. & and | are bit-wise operators. They evaluate their second operand if evaluation of the first operand
will determine the result of the operation. 2. && and || are short-circuit operators. They do not evaluate their second operand if evaluation of the first operand will determine the result of the operation.

Determine the effect upon objects and primitive values of passing variables into methods and performing assignments or other modifying operations in that method.

1. In Java all the primitives and object references are passed by value. 2. In case of object references, what actually gets passed is a copy of the reference. But, still that 3.
reference can be used to modify the content of the object, as it also points to the same object. If any changes are made to the value of passed data in the method, the changes are not reflected in the calling method, as they are merely copies of the original data.

SECTION 6: OVERLOADING, OVERRIDING, RUNTIME TYPE AND OBJECT ORIENTATION


State the benefits of encapsulation in object oriented design and write code that implements tightly encapsulated classes and the relationships "is a" and "has a". Overloading and Overriding 1. The overriding method should have the exact signature as of the overridden method. 2. The overloaded method should have their argument different. Java does not care about the return value of the overloaded methods. 3. The access modifier of overriding method should be equal or more accessible than the overridden method. 4. Overriding method should throw only the exception thrown by the overridden method or the subclass of the exception. They should throw no new checked exceptions. 5. Attributes are not overridden. 6. Whenever you access a field from outside the class, the declared type of the reference is used rather than the type of the object it refers to. 7. Regardless of the type of the reference, a method will always access its own fields rather than those of a derived class Write code to invoke overridden or overloaded methods and parental or overloaded constructors; and describe the effect of invoking these methods.

1. Parental constructors can be called by using super.<constructor name(arguments)>.


9/7/2012 Wipro Technologies Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

18 2. Overloaded constructors can be called by using this.<constructor name(arguments)>. 3. Call to this() and super() always must be first statement in constructor. 4. If there is no explicit constructor call, compiler automatically inserts a default constructor call of the
super class. There is a cascading effect in this case. 5. When RTTI (Run Time Type Identification) comes in picture, always the method of the object, the object reference points to, is called.

Write code to construct instances of any concrete class including normal top level classes and nested classes. Top Level Classes 1. Can have public or default access. 2. Can be final or abstract, but both can't be combined at the same time. 3. Can't be declared static. 4. Can declare a variable of the same name as of the class. Inner Classes 1. Can be public, private, protected or default. 2. Can be final or abstract also. 3. Can be static or non-static. 4. When static, the enclosing class instance is not required. 5. When non-static, enclosing class instance is required. 6. Can't have static member variables except compile time constants (static final) Inner classes within a method 1. Can't be static. 2. Can have only default access, no private, protected or public permitted here. 3. Can have final or abstract modifiers. 4. Can access anything from the enclosing class. 5. Can access only the final variables in the parameter list or the variable defined inside the enclosing method. 6. Forward instantiation is not allowed. Anonymous Inner Classes 1. Can either extend a class or implement an interface. 2. Cant provide its own constructors. 3. Can have arguments when the constructor of the super class it extend, has those.

SECTION 7: THREADS
Write code to define, instantiate and start new threads using both java.lang.Thread and java.lang.Runnable.

1. A thread can be created in two ways: (i) Extending java.lang.Thread, giving the definition of run()
method, creating an instance of that object and calling the start() method. (ii) Implementing java.lang.Runnable, giving the definition of run(), passing an object of the class to a Thread object and calling the start() method of the Thread object.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

19 2. A run() method has to be declared as public void run(). Any other declaration of the run() method 3. 4.
will not cause the thread to execute, as the class doesnt provide the implementation for the expected run method. There will not be any compilation error though the signature of run() method is different from the one expected. If run() method is called directly instead of calling the start() method, it will behave as a single thread of execution, just like any other method call, i.e., no thread will be created.

Recognize conditions that might prevent a thread from executing.

1. Methods like wait(), sleep() and yield(). 2. Entering a synchronized region can also force the thread to pause until it obtains a lock on the
object.

3. CPU scheduling can also cause the thread to pause for some time. 4. Deadlocks can also cause the thread to pause. If two threads are unable to recover from a 5.
deadlock, they will be in that state forever. Deadly embrace is a scenario, where one thread has a lock on object A and waiting to acquire lock on object B. At the same time, another thread has a lock on object B and waiting to acquire lock on object A.

Write code using synchronized wait, notify and notifyAll to protect against concurrent access problems and to communicate between threads.

1. wait(), notify() and notifyAll() should be called only in synchronized block or in synchronized
methods.

2. A thread should have the object lock prior to attempting to execute any of the methods wait(),
notify() and notifyAll(). If this is not followed, an exception will be thrown. 3. A thread can obtain the lock on an object only when it enters a synchronized block. 4. Not more than one thread can execute in a synchronized block.

Define the interaction among threads and object locks when executing synchronized wait, notify or notifyAll. 1. Every object instance has a lock associated with it. 2. If a tread requires a lock on an object, and if the lock is acquired by any other object, the thread must wait for the lock to be released. 3. A thread must hold the lock of the object on which it is issuing a wait() call. 4. As soon as a thread issues wait(), it relinquishes the lock and becomes non-runnable and blocked. After this time, it keeps waiting for notification. 5. If there are multiple threads in the thread pool waiting on the same object, there is no guarantee which thread will get the lock of the object after issuing a notify() or notifyAll() and become runnable. 6. There can be scenarios where a thread never gets a chance to become runnable. 7. Increasing the priority of a thread though not ensures but makes the chances of becoming runnable better once a notify() or notifyAll() is issued.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

20

SECTION 8: FUNDAMENTAL CLASSES IN THE JAVA.LANG PACKAGE


Write code using the following methods of the java.lang.Math class: abs, ceil, floor, max, min, random, round, sin, cos, tan, sqrt.

1. abs() returns the absolute value of the argument. There are four overloaded version of abs() which 2. 3. 4. 5. 6. 7. 8.
take int, long, float and double as argument, and return the result of the same data type. E.g. abs(2) = 2; abs(-2) = 2; abs(0) = 0. ceil() returns the nearest integer greater than the argument. It takes a double and returns a double. E.g. ceil(4.5) = 5; ceil(-4.5) = -4. floor() returns the nearest integer smaller than the argument. It takes a double and returns a double. E.g. floor(4.5) = 4; floor(-4.5) = -5. max() and min() return greater and smaller of the two arguments respectively. There are four overloaded version of max() and min() which take int, long, float and double as argument, and return the result of the same data type. random() returns a random double value. 0 <= returned value < 1. round() has 2 overloaded version which take float and double as argument and return int and long respectively. The first version returns the int closest to the float argument. The second version returns the long closest to the double argument. sin(), cos() and tan() take double as argument and return double. All the angles are measured in radians, not in degrees. There is no need of knowing the technical definitions of them from exam point of view. sqrt() takes a double argument and returns a double square root value. If the argument is negative, the return value id Double.NaN. No exception is thrown in this case.

Describe the significance of the immutability of String objects.

1. String objects are always immutable in all the cases. Calling one of the Strings data modification
method or reassigning an instance variable of type String. 2. The index of the String ranges from 0 to length()-1. 3. String s1 = new String("My String"); String s2 = s1; Here s1 and s2 both will contain the same reference, so both will be equal (==). 4. String s1 = "abc"; String s2 = "abc"; Here s1 and s2 both are String literals instead of String objects. So, once "abc" is created in the String Pool, it will be reused in case of creating S2. It means that after the creation, saying either S1 or S2 both is the same thing. So, both will be equal (==).

5. String s1 = new String("My String");


String s2 = new String("My String"); In this case, s1 and s2 both are different String objects created at different memory locations on the heap. So, both will never be equal (==) though they point to the same String literal in the String Pool.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

21
Describe the significance of wrapper classes, including making appropriate selections in the wrapper classes to suit specified behavior requirements, stating the result of executing a fragment of code that includes an instance of one of the wrapper classes, and writing code using the following methods of the wrapper classes (e.g., Integer, Double, etc.): doubleValue floatValue intValue longValue parseXxx getXxx toString toHexString Please refer to books in Resources section.

SECTION 9: THE COLLECTIONS FRAMEWORK


Make appropriate selection of collection classes/interfaces to suit specified behavior requirements. 1. Following is the hierarchy of Collections framework. Knowing this hierarchy and the function of each of the implementing classes are enough to answer any question in the exam.

Implementations
Hash Table Resizable Array

Interfaces

2. 3.

4.

5.

6.

7.

Set HashSet List ArrayList LinkedList Map HashMap TreeMap LinkedHashMap HashSet This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. HashMap This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. ArrayList Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.) TreeSet This class implements the Set interface, backed by a TreeMap instance. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used. TreeMap Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used. LinkedList Linked list implementation of the List interface. Implements all optional list operations, and permits all elements (including null). In addition to implementing the List interface, the LinkedList class provides uniformly named methods to get, remove and insert an element at the beginning and end of the list. These operations allow linked lists to be used as a stack, queue, or double-ended queue (deque). Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes Issue: 2

Balanced Tree TreeSet

Linked List

Hash Table + Linked List LinkedHashSet

9/7/2012 Wipro Technologies

22 8. LinkedHashSet Hash table and linked list implementation of the Set interface, with predictable
iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.) LinkedHashMap Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.) A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches.

9.

Distinguish between correct and incorrect implementations of hashCode methods. 1. You must override the hashCode() in each and every class which overrides equals(). Otherwise it will a violation of the contract. 2. Whenever it is invoked on the same object more than once during an execution of an application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. 3. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. 4. It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables. 5. Equal objects must have equal hash codes. 6. A good hash function tends to produce unequal hash codes for unequal objects. 7. It is acceptable to exclude redundant fields from the hash code computation. In other words, it is acceptable to exclude any field whose value can be computed from fields that are included in the computation. It is required that you exclude any fields that are not used in equality comparisons. 8. Do not be tempted to exclude significant parts of an object from the hash code computation to improve performance.

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

23

Resources
Web Sites
The best site in the world to learn Java the fun way and for preparation for SCJP also: http://www.javaranch.com/ Some humor here too, but lots of extremely useful info also. http://www.mindprod.com/jgloss/jgloss.html Good sites for SCJP preparation: http://www.jchq.net http://www.javaprepare.com

Sites for SCJP exam. They are worth visiting... http://www.jchq.net/tutorial/introj2.html Last minute revision of the concepts and many sample questions... http://www.jchq.net/mockexams/exam1.htm http://www.jchq.net/mockexams/exam2.htm http://www.javaranch.com/maha/_Mock_Exams/JohnJuntMockExam.htm http://www.danchisholm.net/ SCJP Mock exams. http://www.jdiscuss.com/Enthuse/jsp/ViewResources.jsp?category=scjp2&subcat=Study+Notes SCJP2: Study Notes Other useful sites: http://sun.java.com http://developer.java.sun.com/developer/onlineTraining/Downloads/ http://developer.java.sun.com/developer/onlineTraining/

Books
1. Java 2 Exam Notes, Phillip Heller 2. Complete Java 2 Certification Study Guide, Robert, Heller & Ernest 3. Java Programmers Reference, Grant Palmer

9/7/2012 Wipro Technologies

Java 2 Standard Edition SCJP for Java 2 Platform 1.4 Preparation Notes

Issue: 2

Potrebbero piacerti anche