Senthilkumar Gopal

Musings of a machine learning researcher, engineer and leader

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

Chapter 1

  1. Read the keywords list
  2. Always check variable, class and method name for the keywords
  3. Variable range is -2(bits – 1)
  4. Ranges of primitive numbers
  5. Octal (max): 21 digits and Hexadecimal (max): 16 digits without leading 0 and 0x
  6. Hexadecimal is case-Insensitive
  7. Octal and Hexadecimal can be used for long also using L suffix
  8. Unicode Character is represented as char x = ‘04E’
  9. char being assigned out of range integer values (above 65535 or -ve numbers needs a cast to (char)
  10. Size should NOT be given when declaring an array int[5] x is wrong
  11. Primitive arrays initialize the variables to default value and Object arrays to null
  12. Negative numbers gives ArrayIndexOutOfBoundsException (RuntimeException)
  13. Arrays has a VARIABLE known as length
  14. Size should NOT be given for anonymous array int[] x = new int[] {4,5}
  15. For primitives, smaller length values (char, byte and short) can be placed in an int array
  16. For Objects, its subclass reference variables can be placed in an Object array
  17. Primitive array variables cannot be assigned there restrictive equivalent variables. Int[] x = char[] {6,7,8}. This is not correct
  18. For Object, array variables CAN be assigned there subclass array variables (unlike primitive variables)
  19. Refer to Default Values for Primitive and Reference types
  20. Class level String variables will be initialized only to NULL
  21. Local and Class Level Array Variables will be initialized when the array is INITIALIZED int[] a = new int[5]; This will make all the values as 0 in the array, irrespective of where it is declared and initialized
  22. Local Variables (primitive and Object references) should always be INITIALIZED before use, or compiler error

Chapter 2

  1. strictfp is only for class and a method and NEVER for a variable. It can be combined with either final or abstract.
  2. If a method is ending with a semicolon then that class and the method should be marked abstract (Not needed for interface).
  3. A class can be marked only public or default access. (Not even Protected is allowed)
  4. If a class has default access, it can be accessed only within the package level (not even above or sub-packages). Not even importing will work.
  5. abstract and final cannot be used on the class at the same time. This will give a compilation error
  6. When a subclass is created, then the methods from the superclass can be accessed by the subclass object or by using this operator (in the subclass methods)
  7. Watch out for public static void main accessing the member variables and methods without an Object reference. (Static method cannot access non-static variables)
  8. Private methods CANNOT be overriden. Even if they have the same name and signature, technically it is NOT overriding
  9. default method can be accessed only if the class accessing belongs to the same package PACKAGE Restriction
  10. Protected method can be accessed through inhertiance though the subclass is from a different package - Package + kids
  11. When a subclass outside the package inherits the protected member (inheritance), the member becomes private to any codce outside the class
  12. Refer to Access to class Members lesson.
  13. The first CONCRETE subclass of an abstract class must implement all abstract methods of the superclasses public void setSpeed(int speed) { speed=speed;}. This will just take the local variable speed. We need to declare it as this.speed (NO compilation error)
  14. Any variables declared as final has to be initialized either in the declaration itself or in the constructor else Compilation error occurs (If it is not marked final, instance variables need not be initialized). Also it cannot be overriden by sub class constructors.
  15. STATIC methods cannot be overriden
  16. abstract methods cannot be declared PRIVATE (compliation error), SYNCHRONIZED, strictfp, native and STATIC synchronized, native and strictfp modifiers can be set only to Methods not variables and classes
  17. Only instance variables can be marked transient and volatile (not methods or classes)
  18. Instance variables can be marked four access levels, final, transient and volatile
  19. Instance variables cannot be marked abstract, synchronized, native and strictfp
  20. Refer to Comparison of modifiers for variables and methods
  21. Local variables don’t get default values and should be initialized before use
  22. Instance variables marked final should be initialized in declaration itself or in the CONSTRUCTOR itself - (Compilation error)
  23. INTERFACE variables are always public static final. So cannot be reassigned
  24. Refer to things that can be static and non-static
  25. Explicit imports are resolved first, then the classes from the current package and last- the implicit imports
  26. for java.lang.Runnable interface question, only one method available is public void run(){}
  27. Refer to Interface Properties
  28. A variable declared in the interface cannot be changed at all
  29. A concrete implementation of an interface need not declare the throws clause of the abstract method, however cannot add any new ones only the subclasses or the class declared in the abstract method itself
  30. Only INTERFACEs can extend more than one interface, but it CANNOT implement any class
  31. Synchronized can be applied to static and final methods
  32. When a class with protected method is created, the method can be accessed ONLY by the subclass ‘this’ or subclass objects WITHIN the class (Super class objects give compilation error).
  33. Outside the subclass, the method cannot be accessed using objects

Chapter 3

  1. Compound operators (+=) have an implicit cast
  2. For divide by zero, integers will give ArithmethicException at runtime, while floating point numbers returns positive or negative infinity(same for using the reminder operator also)
  3. The Sysouts works from left to right. If the left and right operand is integer then the result is integer else if one of them is a string then the result is a string
  4. Watch out for increment/decrement operators on a FINAL variable
  5. For >> (right shift), the sign bit gets copied over. Hence the sign remains the same(-ve number remains negative). For << (left shift) the right side is ALWAYS FILLED with zeroes
  6. >>> (UNSIGNED Right Shift) always fills the left side with zeroes irrespective of the sign bit.Hence this shift always gives a positive number
  7. When the shift number is greater than the bit length, then the reminder is used for shifting. Ex: int x = 2; x >>= 34. This actually means x >>= 2 where 34%32 = 2
  8. <<Right Shift divides the number by 2^bits(Ex: x >> 3 means x/2^3)
  9. <<Left Shift multiplies the number by 2^bits(Ex: x << 3 means x * 2^3)>>
  10. <<& - Logical AND; | - Logical OR; ^ - Exclusive OR; ~ - Bitwise compliment>>
  11. Refer to Values of the Truth table
  12. SHORT CIRCUIT Operators work only with Boolean Expressions and NOT with numbers.
  13. However, the logical AND and OR can work with both shadowing Primitives and Object references
  14. Watch out for EXOR being mistaken for power of (Always use Math.power of)
  15. Always & takes precedence over | . So & is evaluated first, in a boolean expression
  16. Whenever any action happens on a String Object, a new String object is created as the result

Chapter 4

  1. The else will always belong to the innermost if which doesn’t have an else
  2. The arguments to switch statement can only be byte,short,char and int
  3. The switch can check only for equality and the case arguments must be determined at runtime. So they have to be either literal constants or final variables
  4. If switch(byte variable) is used, then if the case value is greater than 127 then COMPILATION error occurs
  5. In switch case, two case literals cannot have the same value
  6. default can be placed anywhere in switch case and it will also follow the rule of fall-through
  7. The scope of the variables declared in the for loop is within the for-loop.
  8. In a For Loop, Initialization is performed and CONDITION is checked before the first execution
  9. Iteration will run after every execution and then only comes out of the loop. However, if break, System,exit or return is given inside the for-loop the iteration is NOT executed
  10. continue should be within a loop while break should be within a loop or switch statement
  11. A try clause Should always have either catch or finally block which should immediately follow the try clause without any statements in between
  12. If the subclass is placed after the superclass in the exception catch, COMPILATION Error occcurs
  13. Any method “ducking” the exception should also declare the throws clause, except for RunTimeExceptions
  14. Error or subclass of Error are always unchecked. So it is not required to catch them
  15. For re-throwing the exceptions also(commonly from a catch block), we need to declare the exceptions
  16. Assertion is always tested for true condition, if the condition returns false, AssertionError is thrown
  17. Ex: asssert (x< y) : "Error statement "+y. The First Expression should always result in a boolean while the second expression should always result in a value ( just like sysout)(Cannot be a call to a void method)
  18. Refer to Legal and Ilegal assert Expressions
  19. assertions are disabled by default. So we can use assert as an identifier. But if we turn on assertions, then assert is a keyword - Turn On: javac -source 1.4 test.ClassName
  20. To Compile without assertions (default) javac -source 1.3 test.ClassName
  21. Enabling assertions while executing : java (-ea or -enableassertions) test.ClassName
  22. Disabling assertions while executing : java (-da or -disableassertions) test.ClassName
  23. The above enabling or disabling can be given without any class or package name for all classes or only at package or class level java -ea da:test.ClassName enables for all except test.ClassName (same for package as well)
  24. Refer to Assertion Command Line switches
  25. AssertionError can be caught but it is not appropriate(non-recommended) AssertionError object is not accessible
  26. Assertion recommendations:
  • Do not use assertions to validate arguments to a public method (needs to be checked mandatorily)
  • Do use assertions to validate arguments to a private method
  • Do not use assertions to validate command-line arguments
  • Do use assertions, even in public methods, to check for cases that you know are never, ever supposed to happen (default of a switch Ex: default: assert false;
  • Do not use assert expressions that can cause side effects (method calls or value changing ones)
  • Do not use assertions in private getters and setters”
  1. If a variable is marked FINAL, always check for any code that changes the value
  2. The VM evaluates all assertion flags from left to right

Chapter 5

  1. getters - Accessors and setters - mutators
  2. When the instance variables are public, watch for questions about whether the values will always be as those set in the settters
  3. IS-A means extends (subclass). IS-A, extends, derived from, Inherited from, instance of, subtype of all means subclassing
  4. HAS-A means having a reference variable of type
  5. Animal a = new Horse(); a can access methods which are ONLY overridden by the Horse Object and CANNOT access methods which are present only in the Horse Class. However, it can access all methods of Animal, though they are not present in the Horse
  6. Animal a = new Horse(); will call the HORSE object eat as the object type is decided by virtual method invocation for OVERRIDING methods
  7. Rules for Overriding:
  • Argument list and type, return type should match
  • Access levels can be less retrictive but CANNOT be more restrictive
  • There cannot be additional broader exceptions thrown, however it can be lesser or narrower (subclass can be thrown)”
  1. Overload can change the return type, however changing ONLY the return type is not a valid overload
  2. Overload can change the argument list, return type, access modifier, can give broader and new exceptions, overloaded in the same or subclass
  3. The REFERENCE Type decides which overloaded method is being called.
  • Overriding - Instance Type (Runtime)
  • Overloading - reference Type (Compile Time)
  1. Refer to Overloaded and Overriden Method Invocations
  2. Refer to Difference between Overloaded and Overriden methods
  3. Watch out for methods with same as the class but with a return type. They are not constructors
  4. If a constructor with arguments is created, a no-arg constructor will NOT be created by default
  5. Abstract classes can have Constructors and are always called when the subclass is instantiated. Interfaces DO NOT have constructors
  6. A constructor can be called only by another constructor using super() or this(), it cannot be called by any other method
  7. A default constructor has the same access modifier as the class, a super() call in the first line and is of no-arg type
  8. If the super class does not have a no-arg constructor, we HAVE to provide the super() call correctly (Compilation Error)
  9. A constructor cannot be overriden but can be overloaded, but only within the same class as it is NOT inherited
  10. A constructor can have only a call to super() or this() and it should be there in the first line
  11. For return values, it can be a value which can be IMPLICITLY cast into the return type (short for an int return type) and a sub class type can be returned for a super class return type

Chapter 6

  1. Refer to String Object Creation count
  2. String.charAt(index) is zero based
  3. Arrays has an ATTRIBUTE length while String has a method length()
  4. String.substring (the String word in the method is in lowercase) has (start,end). Start is zero-indexed and End is 1-indexed
  5. StringBuffer are ideal for file I/O for handling large streams of data
  6. StringBuffer methods are Synchronized
  7. StringBuffer.insert(offset,String). Offset is Zero-indexed
  8. abs method has all four numerical types as arguments
  9. ceil and floor takes only a double and returns a double
  10. max and min takes all four types of arguments but arg1 and arg2 should be of the same type. However for arguments, they are implicitly CAST. Eg: Math.max(23.5, 3) or Math.max(a,b) where a is int and b is float
  11. random generates a number between 0.0 <= x < 1.0
  12. round takes a float or double and returns a int or long
  13. sin,cos, tan and SQRT takes only double (radians) and returns a double
  14. toDegree and toRadian takes and returns a double
  15. Refer to Important static Math methods
  16. Wrapper classes Float and Double has POSITIVE_INFINITY and NEGATIVE_INFINITY
  17. Double.isNAN(x) is used for testing numbers
  18. Math.sqrt(-16d) results in NaN
  19. divide by 0 for floating point number works while for integers gives ArithmeticException
  20. Refer to Wrapper Class Constructor Arguments
  21. valueOf is present for Integer, Long,Byte and Short and is used as Integer.valueOf("1001101", 2) => 43. i.e., takes two arguments String and radix and returns a WRAPPER class
  22. intValue and parseInt returns a primitive number
  23. Refer to Wrapper Conversion Methods (Important)
  24. The 3 types of toString usages are:
  • obj.toString();
  • Double.toString(3.3d) (All wrapper class has this except Boolean and Character)
  • Long.toString(254,16) => fe (Integer and Long)
  1. Integer and Long has these methods also.
  • Integer.toBinaryString(), toHexString() and toOctalString()
  1. Watch out for usage of StringBuffer methods like append(), reverse(0 on string Objects which leads to Compilation Error

Continued in Part 2