- Wed 03 September 2008
- Notes
- #java, #certification, #library, #coding, #development, #scjp, #kathy, #sierra
Chapter 1
- Read the keywords list
- Always check variable, class and method name for the keywords
- Variable range is -2(bits – 1)
- Ranges of primitive numbers
- Octal (max): 21 digits and Hexadecimal (max): 16 digits without leading 0 and 0x
- Hexadecimal is case-Insensitive
- Octal and Hexadecimal can be used for long also using L suffix
- Unicode Character is represented as char x = ‘04E’
- char being assigned out of range integer values (above 65535 or -ve numbers needs a cast to (char)
- Size should NOT be given when declaring an array int[5] x is wrong
- Primitive arrays initialize the variables to default value and Object arrays to null
- Negative numbers gives ArrayIndexOutOfBoundsException (RuntimeException)
- Arrays has a VARIABLE known as length
- Size should NOT be given for anonymous array int[] x = new int[] {4,5}
- For primitives, smaller length values (char, byte and short) can be placed in an int array
- For Objects, its subclass reference variables can be placed in an Object array
- Primitive array variables cannot be assigned there restrictive equivalent variables. Int[] x = char[] {6,7,8}. This is not correct
- For Object, array variables CAN be assigned there subclass array variables (unlike primitive variables)
- Refer to Default Values for Primitive and Reference types
- Class level String variables will be initialized only to NULL
- 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
- Local Variables (primitive and Object references) should always be INITIALIZED before use, or compiler error
Chapter 2
strictfp
is only for class and a method and NEVER for a variable. It can be combined with either final or abstract.- If a method is ending with a semicolon then that class and the method should be marked abstract (Not needed for interface).
- A class can be marked only public or default access. (Not even Protected is allowed)
- 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.
- abstract and final cannot be used on the class at the same time. This will give a compilation error
- 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)
- Watch out for public static void main accessing the member variables and methods without an Object reference. (Static method cannot access non-static variables)
- Private methods CANNOT be overriden. Even if they have the same name and signature, technically it is NOT overriding
default
method can be accessed only if the class accessing belongs to the same package PACKAGE Restriction- Protected method can be accessed through inhertiance though the subclass is from a different package - Package + kids
- When a subclass outside the package inherits the protected member (inheritance), the member becomes private to any codce outside the class
- Refer to Access to class Members lesson.
- 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) - 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.
- STATIC methods cannot be overriden
- 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
- Only instance variables can be marked transient and volatile (not methods or classes)
- Instance variables can be marked four access levels, final, transient and volatile
- Instance variables cannot be marked abstract, synchronized, native and strictfp
- Refer to Comparison of modifiers for variables and methods
- Local variables don’t get default values and should be initialized before use
- Instance variables marked
final
should be initialized in declaration itself or in the CONSTRUCTOR itself - (Compilation error) - INTERFACE variables are always public static final. So cannot be reassigned
- Refer to things that can be static and non-static
- Explicit imports are resolved first, then the classes from the current package and last- the implicit imports
- for
java.lang.Runnable
interface question, only one method available is public void run(){} - Refer to Interface Properties
- A variable declared in the interface cannot be changed at all
- 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
- Only INTERFACEs can extend more than one interface, but it CANNOT implement any class
- Synchronized can be applied to static and final methods
- 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).
- Outside the subclass, the method cannot be accessed using objects
Chapter 3
- Compound operators (+=) have an implicit cast
- 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)
- 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
- Watch out for increment/decrement operators on a FINAL variable
- 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 >>>
(UNSIGNED Right Shift) always fills the left side with zeroes irrespective of the sign bit.Hence this shift always gives a positive number- 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 meansx >>= 2
where34%32 = 2
- <<Right Shift divides the number by
2^bits(Ex: x >> 3 means x/2^3)
- <<Left Shift multiplies the number by
2^bits(Ex: x << 3 means x * 2^3)
>> - <<
& - Logical AND; | - Logical OR; ^ - Exclusive OR; ~ - Bitwise compliment
>> - Refer to Values of the Truth table
- SHORT CIRCUIT Operators work only with Boolean Expressions and NOT with numbers.
- However, the logical AND and OR can work with both shadowing Primitives and Object references
- Watch out for EXOR being mistaken for power of (Always use Math.power of)
- Always
&
takes precedence over|
. So&
is evaluated first, in a boolean expression - Whenever any action happens on a String Object, a new String object is created as the result
Chapter 4
- The else will always belong to the innermost if which doesn’t have an else
- The arguments to switch statement can only be byte,short,char and int
- 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
- If switch(byte variable) is used, then if the case value is greater than 127 then COMPILATION error occurs
- In switch case, two case literals cannot have the same value
default
can be placed anywhere in switch case and it will also follow the rule of fall-through- The scope of the variables declared in the for loop is within the for-loop.
- In a For Loop, Initialization is performed and CONDITION is checked before the first execution
- 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
continue
should be within a loop while break should be within a loop or switch statement- A try clause Should always have either catch or finally block which should immediately follow the try clause without any statements in between
- If the subclass is placed after the superclass in the exception catch, COMPILATION Error occcurs
- Any method “ducking” the exception should also declare the throws clause, except for RunTimeExceptions
- Error or subclass of Error are always unchecked. So it is not required to catch them
- For re-throwing the exceptions also(commonly from a catch block), we need to declare the exceptions
- Assertion is always tested for true condition, if the condition returns false, AssertionError is thrown
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)- Refer to Legal and Ilegal assert Expressions
- 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
- To Compile without assertions (default)
javac -source 1.3 test.ClassName
- Enabling assertions while executing :
java (-ea or -enableassertions) test.ClassName
- Disabling assertions while executing :
java (-da or -disableassertions) test.ClassName
- 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) - Refer to Assertion Command Line switches
- AssertionError can be caught but it is not appropriate(non-recommended) AssertionError object is not accessible
- 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”
- If a variable is marked FINAL, always check for any code that changes the value
- The VM evaluates all assertion flags from left to right
Chapter 5
- getters - Accessors and setters - mutators
- When the instance variables are public, watch for questions about whether the values will always be as those set in the settters
- IS-A means extends (subclass). IS-A, extends, derived from, Inherited from, instance of, subtype of all means subclassing
- HAS-A means having a reference variable of type
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 HorseAnimal a = new Horse(); a.eat()
will call the HORSE object eat as the object type is decided by virtual method invocation for OVERRIDING methods- 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)”
- Overload can change the return type, however changing ONLY the return type is not a valid overload
- Overload can change the argument list, return type, access modifier, can give broader and new exceptions, overloaded in the same or subclass
- The REFERENCE Type decides which overloaded method is being called.
- Overriding - Instance Type (Runtime)
- Overloading - reference Type (Compile Time)
- Refer to Overloaded and Overriden Method Invocations
- Refer to Difference between Overloaded and Overriden methods
- Watch out for methods with same as the class but with a return type. They are not constructors
- If a constructor with arguments is created, a no-arg constructor will NOT be created by default
- Abstract classes can have Constructors and are always called when the subclass is instantiated. Interfaces DO NOT have constructors
- A constructor can be called only by another constructor using super() or this(), it cannot be called by any other method
- A default constructor has the same access modifier as the class, a super() call in the first line and is of no-arg type
- If the super class does not have a no-arg constructor, we HAVE to provide the super() call correctly (Compilation Error)
- A constructor cannot be overriden but can be overloaded, but only within the same class as it is NOT inherited
- A constructor can have only a call to super() or this() and it should be there in the first line
- 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
- Refer to String Object Creation count
String.charAt(index)
is zero based- Arrays has an ATTRIBUTE length while String has a method length()
String.substring
(the String word in the method is in lowercase) has (start,end). Start is zero-indexed and End is 1-indexed- StringBuffer are ideal for file I/O for handling large streams of data
- StringBuffer methods are Synchronized
StringBuffer.insert(offset,String)
. Offset is Zero-indexedabs
method has all four numerical types as argumentsceil
andfloor
takes only a double and returns a doublemax
andmin
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)
orMath.max(a,b)
where a is int and b is floatrandom
generates a number between 0.0 <= x < 1.0round
takes a float or double and returns a int or long- sin,cos, tan and SQRT takes only double (radians) and returns a double
toDegree
andtoRadian
takes and returns a double- Refer to Important static Math methods
- Wrapper classes Float and Double has POSITIVE_INFINITY and NEGATIVE_INFINITY
Double.isNAN(x)
is used for testing numbersMath.sqrt(-16d)
results in NaN- divide by 0 for floating point number works while for integers gives ArithmeticException
- Refer to Wrapper Class Constructor Arguments
valueOf
is present for Integer, Long,Byte and Short and is used asInteger.valueOf("1001101", 2) => 43
. i.e., takes two arguments String and radix and returns a WRAPPER classintValue
andparseInt
returns a primitive number- Refer to Wrapper Conversion Methods (Important)
- 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)
- Integer and Long has these methods also.
- Integer.toBinaryString(), toHexString() and toOctalString()
- Watch out for usage of StringBuffer methods like append(), reverse(0 on string Objects which leads to Compilation Error
Continued in Part 2