- Mon 08 September 2008
- Notes
- #java, #certification, #library, #coding, #development, #scjp, #kathy, #sierra
I recently completed the Sun Certified Java Programmer from Sun Microsystems and thought of sharing my notes and gotchas from the Kathy Sierra SCJP preparation book which was the best material to prepare for this certification. All the below notes are material extracted from this link:https://www.amazon.com/SCJP-Certified-Programmer-Java-310-065/dp/0071591060[Kathy Sierra’s book]. The below notes are from the 2008 edition and might not be reflective of the latest Chapter specifics.
This is the continuation of Continued in Part 1 notes.
Chapter 7
- Comparing two reference variables of different hierarchies gives COMPILATION error
- STRINGBUFFER does NOT have an overridden equals method. However, STRING and WRAPPER classes have them
equals()
=> Reflexive (x.x), Symmetric (x.y) and Transitive (x.y.z) and consistent- If two objects are equal then their hashcodes should be equal
equals()
takes OBJECTas parameter and returns boolean. Hashcode() returns int- Refer to Hashcode Contract and Table
- Refer to Types of Collections
- Only List and Set extend Collection not Map
java.util.Collection
is the Superclass for List and Set whilejava.util.Collections
is the class with utilities- Refer to Collection Class Hierarchy
- An implementation of collection can NEVER be Unordered if it is sorted but all other combinations is possible
- HashSet - UnOrdered and UnSorted. LinkedHashSet - Ordered and UnSorted
- Vector(synchronized) and ArrayList are the Only to classes to implement RandomAccess
- LinkedHashSet can be iterated in the Order of Entry or in the Order of Last accessed(useful for caching)
- TreeSet uses a Red-Black Structure for the natural Ordering and has a constructor for defining the natural ordering of the Objects
- Hashtable is synchronized and does NOT allow a null key while HashMap is not synchronized and allows one null key
- Refer to Collection Interfaces and Concrete Implementation Classes
Chapter 8
- Top Level Nested Class is an Inner class marked static
- When trying to create an innerclass object outside the Outer Class
or in a Static method of the Outer Class, we need to CREATE an Object of
the Outer class -
MyOuter.Myinner inObj = new MyOuter().new MyInner();
- To Access the this object, the outer class this is referred as MyOuter.this within the innerclass instance members
- The Inner class members can be STATIC only if the inner class itself is declared as STATIC
- Modifiers for the CLASS LEVEL inner class are : final, abstract, public (allowed for all classes), private, protected and static (only for inner classes)
- Modifiers for the METHOD LEVEL inner class are: abstract and final (cannot be used together)
- Method Level inner Class CANNOT access the method local variables unless it is marked final
- It can access the class level variables
- The class can be instantiated only within the method and it has to be done only after the class declaration is completed
Animal h = new Horse();
Here since the object is determined at runtime ONLY THE OVERRIDEN METHODS of HORSE can be accessed and the Animal methods can be accessed- For Anonymous Inner Class, we CANNOT create an altogether new Class. We have to either extend or implement any existing class. This means we can only OVERRIDE the methods available and NO new methods can be added in Anonymous Inner Class(though new methods can be added, they CANNOT be accessed at all outside the anonymous class as the object type would be that of the superclass used.
- In anonymous Inner class when you access the class object, it extends or implements the superclass implicitly, hence the Constructors will be called when the class instance is accessed
Runnable r = new Runnable()
; (compilation Error) as Runnable is an Interface. However,Runnable r = new Runnable() {public void run(){}};
is vaild- When the anonymous class is created within the argument of a method,
the closing semicolon appears after the argument close bracket.
###> });
- A static nested class does not have acccess to the member and instance variables of the outer class. Look out for questions which does this
- Normal Class:
MyOuter.MyInner inObj = new MyOuter().new MyInner();
- Static Class:
MyOuter.MyInner inObj = MyOuter.MyInner();
- Static Nested Class can have both static and non-static members but can access ONLY the static members of the outer class
- When an anonymous class implements an interface, it should override the abstract methods else compilation error occurs
- Check for the CORRECT Presence of the Semicolons before going into
the syntax and logic checking for inner classes
Object o = new Horse("zippo"); Horse h = (Horse) o; o.eat();
- If the cast to Horse is not done, then the object can access only the OBJECT methods and the Horse Overriden ones only
Chapter 9
start()
,run()
,yield()
andsleep()
- Important methods in Threads- Types of Instantiating a Thread Class:
- Extends Thread -
MyThread t = new MyThread();
- Implements Runnable -
MyRunnable r = new MyRunnable(); Thread t = new Thread(r);
- Calling the
run()
DOES NOT start a new stack though its legal. We have to uset.start()
for starting the execution in a new stack - Methods for Influencing Execution Control of Threads
- java.lang.Thread - static sleep(long), static yield(), final join(), final setPriority(int)
- java.lang.Object - final wait, final notify, final notifyAll()”
sleep
- guaranteed to sleep for the given time except InterruptedExceptionyield
- gives control back, not guaranteed not to runjoin
- guaranteed to stop execution until the joined thread completes- All these three above methods keeps the lock acquired.
- Notes about synchronized block:
- Only methods can be synchronized
- Only one lock
- No need to synchronize all the methods in a class
- multiple threads can still access the non-synchronized methods
- When a thread goes to sleep, it takes the lock with it
- when a thread acquires a lock on an object, no other method can access any of the synchronized methods in the class
- A thread can have multiple locks
wait
,notify
andnotifyAll
(methods of java.lang.Object) should be called from within a synchronized block because it has to own the lock before waiting or notifying else will get IllegalMonitorStateException- Even when notify is called, the object lock will NOT be released until the end of the synchronized block
- Refer to Key Thread Methods
- Check for
sleep()
orwait()
method without a try-catch block for checked (InterruptedException) - Check for the same thread being started twice
- Check for synchronized being used on an non-object
- Synchronizing the code that calls the calculating method DOES NOT synchronize the action, the synchronized block needs to be applied to the method doing the actual calculation.
- Don’t synchronize the run() method or the code inside it as there might be multiple threads created and each will have its own run method. So synchronize the called method
- When two threads are created and a single object is used for accessing the methods, the wait, notify should be within synchronized block as the thread should own the lock of the object before the methods are called. Otherwise, it will throw a runtime exception
- When superclass object reference is used for a sub class object, only the OVERRIDEN methods can be accessed and the variables if printed are from SUPER CLASS only
- return type should always be immediately before the method name or compilation error
- A reference passed into a method is passed as if it were a copy of a pointer pointer rather than the actual object. Thus if that reference is assigned to a null it makes no difference to any other copy of that pointer. Thus the code within the method findOut makes no difference to any other references. Although reference z is assigned to null reference y still points to the object so no objects are eligible for garbage collection.
- Because of the way twos complement number representation works the unsigned right shift operation means a small shift in a negative number can return a very large value so the output of option 1 will be much larger than 10.
- The unsigned right shift places no significance on the leading bit that indicates the sign. For this shift the value 1 of the bit sign is replaced with a zero turning the result into a positive number for option 2.
- Shifting can be done only on int, short or byte NOT on long and ALWAYS returns an int (32 bit)
- If shifting is done on a long, then the result is always a long (64 bit)
- An else clause always belongs to the innermost if without an else, irrespective of the indentation
- In switch case, no two variables can be same
- If switching on a byte, case 128 gives compilation error
- Only final int can be used in a case, since the value must be confirmed at compile time
- assertions are for situations that will never happen
assert(true check)
- Throws AssertionError if the tests failedassert(check) : expression
- check is always boolean and expression is never void- assert is a keyword
- If there is any statement between the label and the loop then, that label is NOT recogonized and hence compliation error occurs. Also, labels can be of the same name and the innermost one is taken into consideration
- Escape slashes are allowed only for b,t,n,f,r, “,’,
#,%
cannot be used in a variable name and a number cannot be used at the start of a variable name- If a variable is final then if the casting lies within the range,
casting is not needed.
final short s1 = 1;
byte s2 = s1;
- compiles correctly- true, false and null are case-SENSITIVE
- A call to the super class method can be done using super.methodname and can be placed anywhere in the method.(Static rule applies).Similarly the superclass variables can be accessed using super.also
- The REFERENCE type decides which overloaded method is being called,
while OBJECT type decides which overriden method is called. In fact,
Animal a = new Horse(); a.eat("Carrots");
give COMPILATION ERROR as the reference type is used for methods present check - When using
super()
orthis()
to invoke constructors, they must be on the first line. Any methods that need to be used needs to be static as the object would not be created until the SUPER constructor completes return (long) x/y
will give float as the cast is only for x. Also int/int gives only int.- ALWAYS check the NUMERATOR and DENOMINATOR For the return type. If wither Num or Denom is float or double then the result is also float or double
Miscellaneous
- First Check for Access Modifiers
- Check for static refering no-static
- Check for illegal subclassing
- Watch for method or class names for keyword list. They are not
keywords -
x=3 ###> ~x = -4 ###> ~x = - (x +1)
int []a3,[]a4;
here after a comma only a variable should be present- ALWAYS remember if one else is executed ,all the other else if/else will NOT be executed
- Even if the called method is static, this can NEVER be used inside a static method
- ### will work correctly for STRING values if No String
Objects are created.
"john"###"john"
works correctly. start()
method is used to schedule a thread for execution- protected void finalize() throws Throwable
- concat() is a method of String while append is for StringBuffer
- All the methods in StringBuffer are synchronized