Senthilkumar Gopal

Musings of a machine learning engineer

Aceing SCJP - Notes from Kathy Sierra Prep book - Part 2


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

  1. Comparing two reference variables of different hierarchies gives COMPILATION error
  2. STRINGBUFFER does NOT have an overridden equals method. However, STRING and WRAPPER classes have them
  3. equals() => Reflexive (x.x), Symmetric (x.y) and Transitive (x.y.z) and consistent
  4. If two objects are equal then their hashcodes should be equal
  5. equals() takes OBJECTas parameter and returns boolean. Hashcode() returns int
  6. Refer to Hashcode Contract and Table
  7. Refer to Types of Collections
  8. Only List and Set extend Collection not Map
  9. java.util.Collection is the Superclass for List and Set while java.util.Collections is the class with utilities
  10. Refer to Collection Class Hierarchy
  11. An implementation of collection can NEVER be Unordered if it is sorted but all other combinations is possible
  12. HashSet - UnOrdered and UnSorted. LinkedHashSet - Ordered and UnSorted
  13. Vector(synchronized) and ArrayList are the Only to classes to implement RandomAccess
  14. LinkedHashSet can be iterated in the Order of Entry or in the Order of Last accessed(useful for caching)
  15. TreeSet uses a Red-Black Structure for the natural Ordering and has a constructor for defining the natural ordering of the Objects
  16. Hashtable is synchronized and does NOT allow a null key while HashMap is not synchronized and allows one null key
  17. Refer to Collection Interfaces and Concrete Implementation Classes

Chapter 8

  1. Top Level Nested Class is an Inner class marked static
  2. 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();
  3. To Access the this object, the outer class this is referred as MyOuter.this within the innerclass instance members
  4. The Inner class members can be STATIC only if the inner class itself is declared as STATIC
  5. Modifiers for the CLASS LEVEL inner class are : final, abstract, public (allowed for all classes), private, protected and static (only for inner classes)
  6. 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
  1. 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
  2. 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.
  3. 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
  4. Runnable r = new Runnable(); (compilation Error) as Runnable is an Interface. However, Runnable r = new Runnable() {public void run(){}}; is vaild
  5. When the anonymous class is created within the argument of a method, the closing semicolon appears after the argument close bracket. ###> });
  6. 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();
  1. Static Nested Class can have both static and non-static members but can access ONLY the static members of the outer class
  2. When an anonymous class implements an interface, it should override the abstract methods else compilation error occurs
  3. 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();
  4. 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

  1. start(), run(), yield() and sleep() - Important methods in Threads
  2. Types of Instantiating a Thread Class:
  • Extends Thread - MyThread t = new MyThread();
  1. Implements Runnable - MyRunnable r = new MyRunnable(); Thread t = new Thread(r);
  2. Calling the run() DOES NOT start a new stack though its legal. We have to use t.start() for starting the execution in a new stack
  3. 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()”
  1. sleep - guaranteed to sleep for the given time except InterruptedException
  2. yield - gives control back, not guaranteed not to run
  3. join - guaranteed to stop execution until the joined thread completes
  4. All these three above methods keeps the lock acquired.
  5. 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
  1. wait, notify and notifyAll(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
  2. Even when notify is called, the object lock will NOT be released until the end of the synchronized block
  3. Refer to Key Thread Methods
  4. Check for sleep() or wait() method without a try-catch block for checked (InterruptedException)
  5. Check for the same thread being started twice
  6. Check for synchronized being used on an non-object
  7. 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.
  8. 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
  9. 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
  10. 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
  11. return type should always be immediately before the method name or compilation error
  12. 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.
  13. 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.
  14. 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.
  15. Shifting can be done only on int, short or byte NOT on long and ALWAYS returns an int (32 bit)
  16. If shifting is done on a long, then the result is always a long (64 bit)
  17. 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
  1. assertions are for situations that will never happen
  2. assert(true check) - Throws AssertionError if the tests failed
  3. assert(check) : expression - check is always boolean and expression is never void
  4. assert is a keyword
  5. 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
  6. Escape slashes are allowed only for b,t,n,f,r, “,’,
  7. #,% cannot be used in a variable name and a number cannot be used at the start of a variable name
  8. If a variable is final then if the casting lies within the range, casting is not needed. final short s1 = 1;
  9. byte s2 = s1; - compiles correctly
  10. true, false and null are case-SENSITIVE
  11. 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
  12. 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
  13. When using super() or this() 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
  14. return (long) x/y will give float as the cast is only for x. Also int/int gives only int.
  15. 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

  1. First Check for Access Modifiers
  2. Check for static refering no-static
  3. Check for illegal subclassing
  4. Watch for method or class names for keyword list. They are not keywords - x=3 ###> ~x = -4 ###> ~x = - (x +1)
  5. int []a3,[]a4; here after a comma only a variable should be present
  6. ALWAYS remember if one else is executed ,all the other else if/else will NOT be executed
  7. Even if the called method is static, this can NEVER be used inside a static method
  8. ### will work correctly for STRING values if No String Objects are created. "john"###"john" works correctly.
  9. start() method is used to schedule a thread for execution
  10. protected void finalize() throws Throwable
  11. concat() is a method of String while append is for StringBuffer
  12. All the methods in StringBuffer are synchronized