Showing posts with label Quick Notes: SCJP 1.6. Show all posts
Showing posts with label Quick Notes: SCJP 1.6. Show all posts

Quick Notes: SCJP 1.6 (Sun Certified Java Programmer)

This articel contains quick notes which I did during reading Sun Certified Programmer for Java 6 Study Guide - SCJP. Kathy Sierra, Bert Bates.

Also it was extended with some additional notes from official Java doc API which are not required for SCJP 6.

If you gonna pass SCJP exam - it will be the best crib.
  

1         DECLARATION & ACCESS CONTROL

1.1     Ranges of Numeric Primitives

Type
Bits
Bytes
Min. Range
-2(bits-1)
Max. Range
2(bits-1)-1
byte
8
1
-27
27-1
short
16
2
-215
215-1
int
32
4
-231
231-1
float
32
4
n/a
n/a
long
64
8
-263
263-1
double
64
8
n/a
n/a

1.2       Comparison of modifiers on variables vs. methods

Local
Variables
Non-local
Variables
Methods
final
final
public
protected
private
static
transient
volatile
final
public
protected
private
static

abstract
synchronized
strictfp
native

1.3       Enumerations

  • An enum can be declared outside or inside a class but not in a method
  • An enum declared outside a class must not be marked static, final, abstract, protected or private
  • An enum can implement any interface
  • Enums can contain constructors, methods, variables and constant class bodies
  • Enum constructors can never be invoked directly in code
  • MyEnum.values() returns an array of MyEnum’s values

2       OBJECT ORIENTATION

2.1     Overriding

  • Appear in subclasses
  • Have the same name as a superclass method
  • Have the same parameter list as a superclass method
  • Have the same return type as a superclass method
  • The throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including its subclasses
  • The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method:
    • if the superclass method is public, the overriding method must be public
    • if the superclass method is protected, the overriding method may be protected or public
    • if the superclass method is package, the overriding method may be packageprotected, or public
    • if the superclass methods is private, it is not inherited and overriding is not an issue

2.2     Overloading

  • Overloaded methods must change the argument list
  • Overloaded methods can change the return type
  • Overloaded methods can change the access modifier
  • Overloaded methods can declare new or broader checked exceptions

2.3     Coupling

  • Coupling refers to the degree to which one class knows about or uses members of another class
  • Loose coupling is the desirable state of having classes that are well encapsulated, minimize references to each other, and limit the breadth of API usage
  • Tight coupling is the undesirable state of having classes that break the rules of loose coupling

2.4     Cohesion

  • Cohesion refers to the degree in which a class has a single, well-defined role or responsibility
  • High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility
  • Low cohesion is the undesirable state of a class whose members support multiple, unfocused roles or responsibilities

3       ASSIGMENTS

3.1     Initialization rules

  • Init blocks execute in the order they appear
  • Static init blocks run once, when the class is first loaded
  • Instance init blocks run every time a class instance is created
  • Instance init blocks run after the constructor’s call to super()

3.2     Boxing

  • Primitive widening uses the “smallest” method argument possible
  • Used individually, boxing and var-args are compatible with overloading
  • You cannot widen and then box (int can’t become Long)
  • You cannot widen from one wrapper type to another (IS-A fails)
  • You can box and then widen (int can become an Object via Integer)
  • You can combine var-args with either widening or boxing

4       OPERATORS

4.1     Bit Shift Operators

Operation
Meaning
Example
>>> 
unsigned shift operator
1011 >>> 1 = 0101
>>, <<
signed shift operator
1011 >> 1 = 1101

5       FLOW CONTROLS

5.1      Exceptions


Picture #5.1 – Hierarchy of Java Exceptions.

5.2     Assertions

5.2.1    Identifier vs. Keyword

  • To use assert as identifier compile code with:
    • javac -source 1.3 *.java
  • To use assert as keyword compile code with:
    • javac -source 1.4/1.5/5/1.6/6 *.java

5.2.2    Assertion Rules

  • Don’t use assertions to validate arguments to a public method
  • Don’t use assertions to validate command-line arguments
  • Don’t use assert expressions that can cause side effects
  • Do use assertions to validate arguments to a private method
  • Do use assertions, even in public methods, to check for cases that you know are never, ever supposed to happen

6       STRINGS,  I/O,  FORMATTING,  PARSING

6.1      String

  • intern() - when the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned. It follows that for any two strings s and t,s.intern() == t.intern() is true if and only if s.equals(t) is true.
  • substring(start, end) - returns a new string that is a substring of this string [start, end)

6.2     StringBuffer & StringBuilder

  • StringBuilder & StrignBuffer are identical in functionality but StringBuilder isn’t thread safe
  • substring(start, end) - returns a new string that is a substring of this string [start, end)
  • equals() – is not overridden; it doesn’t compare values

6.3     Console

Example:
  1 //Get a Console
  2 java.io.Console c = System.console();
  3            
  4 //Read string
  5 String input1 = c.readLine();
  6 String input2 = c.readLine("%s", "input string");
  7            
  8 //Read password
  9 char password[];
 10 password = c.readPassword();
 11 password = c.readPassword("%s", "input password");

6.4     Serialization

  • If a superclass implements Serializable, then its subclasses do automatically
  • If a superclass doesn’t implement Serializable, then when a subclass object is deserialized, the superclass constructor will be invoked, along with its super constructor(s)
  • If a class has object reference to another class that doesn’t implement Serializable the runtime exception will be thrown – java.io.NotSerializableException
  • Serialization is not for Statics

6.5     Dates, Numbers, Currency

Class
Key Instance Creation Options
util.Date
new Date();
new Date(long millisecondsSince01011970);
util.Calendar
Calendar.getInstance();
Calendar.getInstance(Locale);
util.Locale
Locale.getDefault();
new Locale(String lang)
new Locale(String lang, String country)
text.DateFormat
DateFormat.getInstance();
DateFormat.getDateInstance();
DateFormat.getDateInstance(style);
DateFormat.getDateInstance(style, Locale);
text.NumberFormat
NumberFormat.getInstance();
NumberFormat.getInstance(Locale);
NumberFormat.getNumberInstance();
NumberFormat.getNumberInstance(Locale);
NumberFormat.getCurrencyInstance();
NumberFormat.getCurrencyInstance(Locale);

6.6      Regular expressions

Metacharacter
Meaning
\d
A digit: [0-9]
\D
A non-digit: [^0-9]
\s
A whitespace character: [ \t\n\x0B\f\r]
\S
A non-whitespace character: [^\s]
\w
A word character: [a-zA-Z_0-9]
\W
A non-word character: [^\w]
.
Any character

Greedy Quantifier
Meaning
*
Zero or more occurrences
?
Zero or one occurrences
+
One or more occurrences
{n}
Exactly n times
{n,}
At least n times
{n,m}
At least n but not more than m times

6.7      Tokenizing

Example:
  1 String str = "Monday,Tuesday,,Thursday,Friday";
  2            
  3 //String split
  4 String[] tokens = str.split(",");         // [Monday,Tuesday,,Thursday,Friday]
  5 int count = tokens.length;                // count = 5
  6            
  7 //StringTokenizer
  8 StringTokenizer tokenizer = new StringTokenizer(str, ",");
  9 int count3 = tokenizer.countTokens();     //count = 4
 10 while (tokenizer.hasMoreTokens()) {
 11       System.out.print(tokenizer.nextToken() + " ");
 12 }                                         // [Monday,Tuesday,Thursday,Friday]

6.8     Formatting

%[arg_index$] [flags] [width] [.precision] conversion char
arg_index
an integer followed directly by a $, this indicates which argument should be printed in this position
flags
“-”      – left justify this argument
“+”     – include a sign (+ or -) with this argument
“0”      – pad this argument with zeroes
“,”      – use locale-specific grouping separators
“(”      – enclose negative numbers in parentheses
width
indicates the minimum number of character to print
precision
indicates the number of digits to print after the decimal point
conversion
b          – boolean
c        – char
d        – integer
f         – floating point
s        – string


7       GENERICS & COLLECTIONS

7.1     Class hierarchy for collections

Picture #7.1 – Hierarchy of Java Collections

7.2     Collections details

Class
Common Features
Individual Features
ArrayList
·   ordered by index position
·   unsorted
·   could have null elements
·  fast iteration
·  fast random access
Vector
·  thread safe
LinkedList
·  fast insertion
·  fast deletion
·  peek() - retrieves, but does not remove, the head (first element) of this list
·  poll() - retrieves and removes the head (first element) of this list
·  offer() - adds the specified element as the tail (last element) of this list
PriorityQueue

·  ordered by natural order
·  could NOT have null element
·  first in first out
HashSet
·  doesn’t allow duplicates

·  unsorted
·  unordered
·  could have null elements
LinkedHashSet
·  ordered
·  could have null elements
TreeSet
·  sorted
·  can’t have null elements
·  ceiling(e) – returns the lowest element >= e, otherwise null
·  floor(e) - Returns the greatest element in this set less than or equal to the given element, or null if there is no such element.
Hashtable
·  unique identifiers
·   unsorted
·   unordered
·   doesn’t allow anything that’s have null
HashMap
·  unsorted
·  unordered
·  allows one null key
·  allows multiple null values
LinkedHashMap
·  ordered
·  allows one null key
·  allows multiple null value
TreeMap
·  ordered
·  sorted by natural order or custom
·  doesn’t allow null key
·  allows multiple null values
·  ceilingKey(key) – returns the lowest key >= key, otherwise null

java.lang.Comparable
java.util.Comparator
public int compareTo(T o)
public int compare(T o1, T o2)
Returns:
·   negative – if this object < anotherObject
·   zero – if this object =  anotherObject
·   positive – if this object > anotherObject
You must modify the class whose instances you want to sort.
You build a class separate from the class whose instances you want to sort.
Only one sort sequence can be created.
Many sort sequences can be created.
Implemented frequently in the API by:
String, Wrapper classes, Date, Calendar…
Meant to be implemented to sort instances of third-party classes.

java.util.Arrays
Description
static List asList(T[])
Convert an array to a List
static int binarySearch(Object[], key)
static int binarySearch(primitive[], key)
Search a sorted array for a given value,return an index or insertion point.
static int binarySearch (T[], key, Comparator)
Search a Comparator-sorted array for a value.
static boolean equals (Object[], Object[])
static boolean equals (primitive [],primitive [])
Compare two arrays to determine if their contents are equal.
static void sort (Object[])
static void sort (primitive[])
Sort the elements of an array by natural order.
static void sort (T[], Comparator)
Sort the elements of an array using a Comparator.
static String toString (Object[])
static String  (primitive[])
Create a String containing the contents of an array.

java.util.Collections
Description
static int binarySearch (List, key)
static int binarySearch (List, key, Comparator)
Search a “sorted” List for a given value,return an index or insertion point.
static void reverse(List)
Reverse the order of elements in a List.
static Comparator reverseOrder()
static Comparator reverseOrder(Comparator)
Returns a Comparator that sorts the reverse of the collection’s current sort sequence.
static void sort(List)
static void sort(List, Comparator)
Sort a List either by natural order or by a Comparator

8       INNER CLASSES

8.1     Class-Local Inner Class

8.1.1    Instantiating

To create an instance of an inner class, you must have an instance of the outer class to tie to the inner class.
Example:
  1 //Example#1
  2 MyOuter mo = new MyOuter();
  3 MyOuter.MyInner inner = mo.new MyInner();
  4            
  5 //Example#2
  6 MyOuter.MyInner inner = new MyOuter().new MyInner();

8.1.2    Member modifiers

Member modifies applied to inner classes:
  • final  
  • abstract      
  • public
  • private
  • protected
  • strictfp
  • static – for static nested class(not inner)

8.2     Method-Local Inner Class

8.2.1    Instantiating

  • method-local inner class can be instantiated only within the method where the inner class is defined
  • The inner class object can’t use the local variables of the method the inner class is in
  • local class declared in a static method has access to only static members of the enclosing class
Example:
  1 public class MyOuter {
  2    int b = 9;
  3    static int s = 9;
  4 
  5    [static] public void myFunc() {
  6       int a = 0;
  7      
  8       class MyInner {
  9          int add(int value) {
 10             value += a;       // Illegal use of local variable 'a'
 11             value += b;       // Legal use of member variable 'b'
 12             [value += s];     // Legal use of static variable 's'
 13             return value;
 14          }
 15       }
 16            
 17       MyInner mi = new MyInner();
 18       mi.add(5);
 19    }
 20 }

8.2.2    Member modifiers

  • The same rules apply to method-local inner classes as to local variable declarations, i.e. you can mark a method-local inner class as abstract or final, but never both at the same time

8.3     Anonymous

8.3.1    Instantiating

  • Inner class declared without any class name at all
  • A semicolon is required after declaration of anonymous class
  • Polymorphism is in play when anonymous inner class are involved
Example:
  1 class MyOuter {
  2       void myFunc() {
  3             System.out.println("MyOuter");
  4       }
  5 }
  6 
  7 class MainClass {
  8       MyOuter mo = new MyOuter() {
  9             void myFunc() {
 10                   System.out.println("Anonymous Class");
 11             }
 12       }; // WATCH OUT about semicolon!
 13      
 14       public void doIt() {
 15             mo.myFunc();      // Legal, MyOuter has a 'myFunc()'
 16             mo.newFunc();     // Not legal! MyOuter doesn't have a 'newFunc()'
 17       }
 18 }

8.4     Static Nested Class

8.4.1    Instantiating

  • The static nested class can be accessed without having an instance of the outer class
  • The static nested class doesn’t have access to the instance variables and non-static methods of the outer class
Example:
  1 class Outer {
  2       static abstract class Nested {
  3             abstract void doIt();
  4       }
  5 }
  6 
  7 class Runing {
  8       static int a = 0;
  9       int b = 0;
 10      
 11       public static void main(String[] args) {
 12             Outer.Nested on = new Outer.Nested() {
 13                   @Override
 14                   void doIt() {
 15                         System.out.println(a);  //OK
 16                         System.out.println(b);  //Not legal!
 17                        
 18                   }
 19             };
 20       }
 21 }

9       THREADS


9.1     Thread states

Picture #9.1

9.2     Class Thread

java.lang.Thread
public Thread()

public Thread(Runnable target)

public Thread(ThreadGroup group, Runnable target)

public Thread(String name)

public Thread(ThreadGroup group, String name)

public Thread(Runnable target, String name)

public Thread(ThreadGroup group, Runnable target, String name)

public Thread(ThreadGroup group, Runnable target, String name, longstackSize)

public final void wait()
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
public final native void notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait() methods.
public final native void notifyAll()
Wakes up all threads that are waiting on this object's monitor. A thread waits on an object's monitor by calling one of the wait() methods.
sleep(long millis)
            throws InterruptedException
sleep(long millisint nanos)
          throws InterruptedException
Causes the currently executing thread to sleep for the specified number of milliseconds. The thread does not lose ownership of any monitors.
yield()
Causes the currently executing thread object to temporarily pause and allow other threads to execute.
currentThread()
Returns a reference to the currently executing thread object.
interrupt()
Interrupts this thread.

Throws:
§  if the current thread cannot modify this thread
§  if this thread is blocked in an invocation of the wait() methods of the Object class, or of the join() or sleep(), methods of Thread class
§  if this thread is blocked in an I/O operation
§  if this thread is blocked in a Selector 
§  if none of the previous conditions hold
§  interrupting a thread that is not alive
join() throws InterruptedException
join(long millis)
    throws InterruptedException
join(long millisint nanos)
    throws InterruptedException
Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.

Throws:
InterruptedException
§  if any thread has interrupted the current thread.
setContextClassLoader(ClassLoader cl)
Sets the context ClassLoader for this Thread. The contextClassLoader can be set when a thread is created, and allows the creator of the thread to provide the appropriate class loader to code running in the thread when loading classes and resources.
First, if there is a security manager, its checkPermission method is called with a RuntimePermission("setContextClassLoader") permission to see if it's ok to set the context ClassLoader.

Throws:
SecurityException
§  if the current thread cannot set the contextClassLoader.


9.3     Synchronization and Locks

Key points about locking and synchronization:
  • Only methods (or blocks) can be synchronized, not variables or classes
  • Each object has just one lock
  • Not all methods in a class need to be synchronized
  • Once a thread acquires the lock on an object, no other thread can enter any of the synchronized methods in that class
  • If a class has both synchronized and non-synchronized methods, multiple threads can still access the class’s non-synchronized methods
  • If a thread goes to sleep, it holds any locks it has – it doesn’t release them
  • A thread can acquire more than one lock
  • Static methods can be synchronized

10    DEVELOPMENT

10.1  Java & Javac 

Execute a class: java [-options] class [args...]
Execute a jar file: java [-options] -jar jarfile [args...]

10.2 Basic search algorithm

Java and Javac use the same basic search algorithm:
  • They both have the same list of places they search, to look for classes
  • They both search through this list of directories in the same order
  • As soon as they find the class they are looking for, they stop searching for that class. In the case that their search lists contain two or more files with the same name, the first file found will be the file that is used
  • The first place they look is in the directories that contain the class that come standard with J2SE
  • The second place they look is in the directories defined by classpaths
  • Classpaths should be thought of as "class search paths." They are lists of directories in which classes might be found
  • There are two places where classpaths can be declared:
    • A classpath can be declared as an operating system environment variable. The classpath declared here is used by default, whenever java or javac are invoked
    • A classpath can be declared as a command-line option for either java or javac. Classpaths declared as command-line options override the classpath declared as an environment variable, but they parsist only for the length of the invocation

10.3  Jar archive

Command
Operation
jar cf jar-file input-file(s)
create a JAR file
jar tf jar-file
view the contents of a JAR file
jar xf jar-file
extract the contents of a JAR file
jar xf jar-file archived-file(s)
extract specific files from a JAR file
java -jar app.jar
run an application packaged as a JAR file (requires the Main-class manifest header)
< applet code = AppletClassName.class
        archive="JarFileName.jar"
        width=width height=height>
</ applet>
invoke an applet packaged as a JAR file

10.4   Javadoc

Include tags in the following order:
* @author      (classes and interfaces only, required)
* @version     (classes and interfaces only, required)
* @param       (methods and constructors only)
* @return      (methods only)
* @exception   (@throws is a synonym added in Javadoc 1.2)
* @see         
* @since       
* @serial      (or @serialField or @serialData)
* @deprecated  

10.5   Annotation

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.
Annotations have a number of uses, among them:
  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings
  • Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth
  • Runtime processing — Some annotations are available to be examined at runtime
There are three annotation types that are predefined by the language specification itself: @Deprecated, @Override, and @SuppressWarnings.


@Deprecated — annotation indicates that the marked element is deprecated and should no longer be used.
Example:
  1 /**
  2  * @Deprecated explanation of why it was deprecated
  3  */
  4  @Deprecated
  5  static void deprecatedMethod() { }

@Override — annotation informs the compiler that the element is meant to override an element declared in a superclass.
Example:
  1 // mark method as a superclass method that has been overridden
  2 @Override
  3 int overriddenMethod() { }

@SuppressWarnings — annotation tells the compiler to suppress specific warnings that it would otherwise generate.  Every compiler warning belongs to a category. The Java Language Specification lists two categories: "deprecation" and "unchecked." To suppress more than one category of warnings, use the following syntax:
@SuppressWarnings({"unchecked", "deprecation"})
Example:
  1 // use a deprecated method and tell compiler not to generate a warning
  2 @SuppressWarnings("deprecation")
  3 void useDeprecatedMethod() {
  4      objectOne.deprecatedMethod(); //deprecationwarning - suppressed
  5 }