

What is middleware?

Client --- 
Middleware(includes servlets,JSP,HTML,XML,webserver) 
legacy Appln or Enterprise Information systems. (e.g. RDBMS, ERP, etc).

The client wants to get the service of legacy application (e.g. database transaction).


J2EE defines client tier-middle tier- and back-end tier.
Middleware contains containers and components.
Containers: Web Container (contains servlets, JSP, HTML, etc), 
            EJB Container (contains business logic).
The containers provide std services by any vendor. The components in
those containers are written by developers. 
The containers may be distributed on different platforms.


.The J2SE API consists of two groups: Core Java and Desktop Java.

    * Core Java provides essential functionality for writing powerful enterprise-worthy programs in key areas such as database access, security, remote method invocation (RMI), and communications, to name a few.
    * Desktop Java consists of deployment products such as Java Plug-in, component modeling APIs such as JavaBeans, graphical user interface (GUI) APIs such as
the Java Foundation Classes (JFC) and Swing, and multimedia APIs such as Java3D.
more on java desktop:
  http://javadesktop.org

 Java 2 Platform, Enterprise Edition (J2EE) provides the APIs and tools you need to create and deploy interoperable Web services and clients.

Web Services/XML APIs
It is easy to write Web services and clients with the J2EE XML APIs. All you do
is pass parameter data to the method calls and process the data returned, or for document-oriented web services, send documents containing the service data back and forth. No low-level programming is needed. The following list describes the Web services/XML APIs.


The Java API for XML Processing (JAXP) supports the processing of XML documents
using Document Object Model (DOM), Simple API for XML Parsing (SAX), and XML Style sheet Language Transformation (XSLT). The JAXP API enables applications to parse and transform XML documents independently of a particular XML processing implementation.

The Java API for XML Registries (JAXR) lets you access business and general-purpose registries over the Web. JAXR supports the ebXML Registry/Repository standards and the UDDI specifications.

The Java API for XML-based RPC (JAX-RPC) uses the SOAP standard and HTTP so client programs can make XML-based remote procedure calls (RPCs) over the Internet.
JAX-RPC also supports WSDL so you can import and export WSDL documents. With JAX-RPC and a WSDL, you can easily interoperate with clients and services running on Java-based or non-Java-based platforms such as .NET.


The SOAP with Attachments API for Java (SAAJ) enables you to produce and consume messages conforming to the SOAP 1.1 specification and SOAP with Attachments note.

Java Technology and Web Services is organized into these subcategories:

        Java Web Services Developer Pack (Java WSDP)
        Java API for XML-Based RPC (JAX-RPC)
        Java API for XML Registries (JAXR)

        Java API for XML Processing (JAXP)
        Java Architecture for XML Binding (JAXB)
        SOAP with Attachments API for Java (SAAJ)
        XML and Web Services Security




Alternatively, check out JConfig:
http://www.tolstoy.com/samizdat/jconfig.html
JConfig is a cross-platform library that fills in many of the gaps in
the core Java API, and makes it possible to work with files, processes,
file types, video monitors, etc. in a much more Windows- and
Mac-friendly manner.


 21. (Sect. 7) I did a read from a Buffered stream, and I got fewer bytes
     than I specified.

     [*] This is the way that BufferedInputStream works up to and including
     the current release. The behavior is so unintuitive that it really
     represents a bug. Javasoft has "resolved" the bug by writing comments
     in the program so that the broken behavior is in the range of legal
     outcomes. Ugh.

     When you instantiate a buffered input stream, you can specify the size
     of buffer it should use. Let's call this the internal buffer. When you
     call read() you can say how many bytes to read. Let's call this the
     request. If the request is smaller than the internal buffer and not a
     multiple of the internal buffer, then the last read returns only the
     odd bytes left in the internal buffer! The more reasonable and
     intuitive behavior would be for the internal buffer to be refilled, so
     that the whole request can be granted.

     For example, if you create a BufferedInputStream with an internal
     buffer of 1000 bytes, and try to read 512 byte chunks, your first read
     will return 512 bytes, but your second read will only return
     (1000-512), or 488, bytes. (Assuming that the file has at least that
     many bytes in it). The following code illustrates the problem.

     // troubleshooting by Tov Are Jacobsen
     import java.io.*;
     class filebug {
         public static void main(String args[])
                       throws FileNotFoundException, IOException  {
         BufferedInputStream bis =
            new BufferedInputStream(
            new FileInputStream("test.txt"), 1000 );
         byte[] buf = new byte[2000];
         int numread;
         System.out.println( "Available: "+bis.available() );
         while (true) {
             numread = bis.read(buf,0,512);
             if (numread<0) break;
             System.out.println( "got "+numread
                                +", avail:"+ bis.available());
         }
       }
     }


     Of course, a valid reason for getting less than you asked for is that
     you asked for more data than is actually available in the Stream, e.g.
     you requested 512 bytes from a file that only contains 40 bytes. In
     general, there are no guarantees about how much data is returned for a
     given buffered input stream read request. To avoid this problem, push a
     DataInputStream on top of your buffered stream. Then you can call
     readFully(), which will do what you want.

     A similar "got less than I asked for" occurs when reading a socket.
     Network protocols frequently packetize data and send it across in
     bursts. Nothing is lost of course, and you are always told how many
     bytes you actually got. You will get the remaining bytes on a
     subsequent read. This happens regardless of the language used. Be sure
     to check the "amount of data returned" when using the read(byte[], int,
     int) method of BufferedInputStream, or when reading from a socket.

 22. (Sect. 7) How do I redirect the System.err stream to a file?

     [*] You cannot assign a new FileOutputStream to System.err, as it is
     final. Instead use the System.setErr() library call, like this:

     FileOutputStream err = new FileOutputStream("stderr.log");
     PrintStream errPrintStream = new PrintStream(err);
     System.setErr(errPrintStream);


     This was introduced with JDK 1.1. There is also a corresponding setIn()
     for redirecting standard in, and a setOut() for standard out.

     Note that you will get a compiler warning about a deprecated construct
     when you do this. PrintStreams are deprecated in favor of PrintWriters,
     which handle Unicode properly. The PrintStream is marked as deprecated
     by marking all its constructors as deprecated. There is no way to
     create the PrintStream needed to redirect System.err or System.out
     without triggering the deprecated warning.

24. (Sect. 7) Is there a way to read a char from the keyboard without
     having to type carriage-return?

     [*] You can do this in a GUI (e.g. in a text component). There is no
     pure Java way to do character-by-character I/O without using a GUI.

2. (Sect. 8) How do I print from a Java program?

     [*] Use the Toolkit.getPrintJob() method

     Component c = this.getParent();
     while (c!=null && !(c instanceof Frame))
         c=c.getParent();
     // With a JComponent use   c=getTopLevelAncestor();

     PrintJob pj = getToolkit().getPrintJob((Frame) c, "test", null);
     Graphics pg = pj.getGraphics();
     printAll(pg);
     pg.dispose();
     pj.end();
 7. (Sect. 8) How do you read environment variables from with a Java
     program?

   java -Dfoo=$foo MyClass (Unix)

     or

     java -Dfoo=%foo% MyClass (Win95/NT)

     This sets the "foo" property to the value of the environment variable
     foo, and makes it available in the System properties. Make sure you do
     not leave any spaces after the -D or around the = sign. Inside the
     program you get the value with:

     String env = System.getProperty("foo");

14. (Sect. 8) Where/why should I use the Enumeration interface?

     And here's how you might look at all the tokens in a String:

     StringTokenizer tokens =
         new StringTokenizer (SomeArbitraryString, "\n", false);

     Enumeration enum = tokens.elements();
     while enum.hasMoreElements()
         System.out.println(enum.nextElement());

     Second answer: Notepad expects to see a "carriage return/line feed"
     pair at the end of each line, rather than just the "newline"
     (line-feed) commonly used on Unix. Use this program to expand all
     newlines,

..how to change \n to \r\n

     /*
      * Usage: jre crlf file1.java file2.java ... fileN.java
       */

     import java.io.*;
     class crlf {
         public static void main(String s[]){
             byte b[]; byte p;
             FileInputStream is;
             BufferedOutputStream os;
             File f;
             for (int i=0; i < s.length;i++){
                 try{
                     f=new File(s[i]);
                     b=new byte[(int)f.length()];
                     is = new FileInputStream(f);
                     is.read(b); is.close();
                     os = new BufferedOutputStream(
                     new FileOutputStream(s[i]),b.length);
                     p='?';
                     for(int j=0; j < b.length; j++){
                         if((p!='\r')&&(b[j]=='\n')) os.write('\r');
                         p=b[j]; os.write(p);
                     }
                     os.flush(); os.close();
                 }catch(IOException e){
                     System.err.println(e.toString());
                 }
             }
         }
     }


 3. (Sect. 11) Where can I find a Swing tutorial?

     [*] There is a Swing tutorial at
     http://java.sun.com/docs/books/tutorial/ui/swing/index.html which is
     part of this tutorial:
     http://java.sun.com/docs/books/tutorial/ui/TOC.html
     There is also a Swing FAQ at http://www.drye.com/java/faq.html
     See also http://www.codeguru.com/java/Swing/index.shtml
     There is a Swing Developer Connection website with white papers and
     examples at http://www.theswingconnection.com/.
     Please let this FAQ maintainer know about other good Swing tutorials
     and online resources.

6.8: How do I version a class?
There is no support for versioning classes in Java 1.0. However in Java 1.1 the serialver tool provides a serialVersionUID for one or more classes you can add to your class as a field. This is used in object serialization.

reading from stdin...

  static int getNextInteger() {
  
    String line;
    DataInputStream in = new DataInputStream(System.in);
    try {
      line = in.readLine();
      int i = Integer.valueOf(line).intValue();
      return i;
    }
    catch (Exception e) {
      return -1;
    }
       
  } // getNextInteger ends here


reading text from inputline :

try {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String str = "";
        while (str != null) {
            System.out.print("> prompt ");
            str = in.readLine();
            process(str);
        }
    } catch (IOException e) {
    }

printing to output file:
     FileOutputStream fout =  new FileOutputStream("test.out");
      // now to the FileOutputStream into a PrintStream
      PrintStream myOutput = new PrintStream(fout);
      myOutput.println(fahr + " " + celsius);

reading from text file:
    import java.io.*;
    FileInputStream fin =  new FileInputStream(args[i]);
    // now turn the FileInputStream into a DataInputStream
      DataInputStream myInput = new DataInputStream(fin);
      try {
        while ((thisLine = myInput.readLine()) != null) { ... }
      catch (Exception e) { ... }

Hello World: The Applet
import java.applet.Applet;    
import java.awt.Graphics; 
              
public class HelloWorldApplet extends Applet {

  public void paint(Graphics g) {
    g.drawString("Hello world!", 50, 25);
  }
  
}

<HTML>
<HEAD>
<TITLE> Hello World </TITLE>
</HEAD>

<BODY>
This is the applet:<P>
<APPLET codebase="classes" code="HelloWorldApplet.class" width=200 height=200 ></APPLET>
</BODY>
</HTML>

Passing Parameters to Applets
import java.applet.Applet;    
import java.awt.Graphics; 
             
public class DrawStringApplet extends Applet {

  String input_from_page;

  public void init() {
    input_from_page = getParameter("String");
  }
  
  public void paint(Graphics g) {
    g.drawString(input_from_page, 50, 25);
  }
  
}

Now you need to create an HTML file that will include your applet. The following simple HTML file will do:

<HTML>
<HEAD>
<TITLE> Draw String </TITLE>
</HEAD>

<BODY>
This is the applet:<P>
<APPLET codebase="classes" code="DrawStringApplet.class" width=200 height=200><PARAM name="String" value="Howdy, there!"></APPLET>
</BODY>
</HTML>

Non-blocking read ?
Use 
import java.io.*;
import java.nio.*;
import java.nio.channels.*;

String host = ...;
InetSocketAddress socketAddress = 
  new InetSocketAddress(host, 80);
channel = SocketChannel.open();
channel.configureBlocking(false);
channel.connect(socketAddress);

Question

    When should I use an InputStream, and when should I use a Reader?
Answer

    * If you're reading data, such as bytes of information, you are best off to use InputStreams and DataInputStream in particular.
    * If you're reading in text, and want to be able to call a readLine() method, its best to use Readers, and BufferedReader in particular.

So what's the difference? Well, DataInputStream's readLine() method is deprecated, because of problems with this method. Readers offer an alternative - though placing a readLine() method in a BufferedReader still seems a little odd to me. Whether its buffered or not has little to do with the fact it can read lines of text - but its easy enough to live with.

------
    How can I tell the type of machine and OS my Java program is running on?
 System.out.println ( System.getProperty("os.arch") + " running " +
			System.getProperty("os.name") ); }


J2SE5.0 support for printf & scanf like things:
The printf function is a new method of the java.io.PrintStream class.
System.out.printf() is now supported.
Also see java.util.Formatter class for sprintf() kind of functionality.
For scanf equivalent, do following:
one can use java.util.Scanner :
    Scanner sc = Scanner.create(System.in);
    int i = sc.nextInt();
    float f = sc.nextFloat(); // String sc.next(String pattern) etc.

note: The java.util.regex.Pattern class can be used to construct a regex.

Use java.util.*  StringTokenizer class to tokenize the string:

String speech = "Four score and seven years ago";
StringTokenizer st = new StringTokenizer(speech); // 2nd arg is opt separator
while (st.hasMoreTokens()) {
   println(st.nextToken());
}
This can be used for formatted input processing. 

Note: You can also use Enumeration to get a snapshot of the set of tokens:
     Enumeration enum = st.elements();
     while enum.hasMoreElements() System.out.println(enum.nextElement());


Q . How can a Java program determine the level of JDK support given by the underlying VM? I.e. is it running in a JDK 1.0.2 or 1.1 VM?

    Ans : Look at the java.version system property with:

    String ver = System.getProperty("java.version");

    There isn't a lot of standardization on the string contents however.
    Another possibility is to try { ... } to load a class that is unique to 
    one release, like this:

    boolean isJDK1_1 = true;
    try {
       // java.awt.Cursor is available only in the 1.1.x JDK
       Class cls = Class.forName("java.awt.Cursor");
    } catch (Exception e) {
       // we should have written 'ClassNotFoundException e',
       // but Communicator generates security exception instead.
       isJDK1_1 = false;
    }
    It can be compiled by any version compiler. 

Note: you can create new instances of dynamically loaded classes as below:
    Object foo =  (Cursor) cls.newInstance(); // etc.


Note:Use javap to verify the class integrity:
     javap verify packageFoo.ClassE
     Class packageFoo.ClassE succeeds



 synchronized (obj) {
     ...                   // synchronized block
 }

JNI equivalent:
 if ((*env)->MonitorEnter(env, obj) != JNI_OK) {
     ... /* error handling */
 }
 ...     /* synchronized block */
 if ((*env)->MonitorExit(env, obj) != JNI_OK) {
     ... /* error handling */
 };


netbeans java tutorial:
http://www.netbeans.org/kb/41/j2ee-tut/


Next to do:
   - Ant tutorial
   - Netbeans sample project
   - javap source code debugging
   - get debuggable lib source for netbeans

- Learned importing existing project:
      -Specify project Folder where build.xml etc would be kept.
      -Specify source folder (can be separate from project folder)
      -build.xml is auto generated

appserver installation msg:
welcome page: /home/thava/SUNWappserver/docs/about.html
start appserver:
  SUNWappserver/bin/asadmin start-domain domain1

start Admin console:
http://localhost:33862
access samples:
http://localhost:33859/samples/index.html

How to create executable jar file ?
% jar cvfm MyApp.jar MyApp.mf *.class *.gif
where MyApp.mf is:
   Main-Class: MyAppMain
   Class-Path: mylib.jar

% java -jar MyApp.jar


On windows what is the diff between java and javaw ?
  javaw does not start with a console where java does.

==================================================================================

Typical notify/wait calls occur in following ways:
Note: When you do wait()/notify(), the executing thread should be the
      monitor for the object on which the wait()/notify() is called.

Case 1:  any one executing the synchronized instance method becomes monitor
         for the "this" object. so the wait()/notify() is actually this.wait()
         and this.notify()

class  xxx {

  synchrnozied public void myfunction(){
        if (condition)  wait();
        .....
        if (another_condition)  notify();
  }

}

Case 2:  Any one who does explicit synchronized on "this" object or any object
         does explicit  notify()/wait()

synchronized (obj) {
      if (condition)  obj.wait();
      ....
      if (another_condition)  obj.notify();
}

Case 3: do explicit synchronized on "this" object. 
        Note that the "this" object need not be of "thread" type here,
        but often this type of usage occurs with in "thread" classes.

synchronized (this) {
      if (condition)  wait();
      ....
      if (another_condition)  notify();
}

==================================================================================


Constructors:

   - class A extends B {
        public A(String s1, String s2){
            super(s1, s2);  // By default, first stmt is super();
            // this(s2, s2, true); reuses 3 arg constructor.
	    // use of super() and this() both allowed at same time
	    // provided super() is called first, and then this().
        }
     }

   - Objects are created from bottom up.
     class A extends Object { int k ; }
     Provides default construtor automatically like this:

        A(){ Create class Reference to "A"; 
             create Parent-Object using this reference;
             Assign k = 0; return this reference. }

   - If the first statement of constructor does not start with "super" then
     automatically "super();" statement is inserted as first statement.

   - If constructor with args is defined, then declaring default constructor
     is mandatory if you want to use that as well.
     *** Watch this out *** If explicit constructor exists, no-arg constructor
         must exist if the class is instantiated at runtime or **extended*
         at compile time.

   - Initialization blocks can be static or non-static.
     Non-static initialization blocks can be used to perform initialization
     for all constructors. (There by eliminating constructor decln if possible)
     e.g. class A (){  int k; static int id = 0;
                       { k = id++; }  /* This is init block. non-static. */
                    }

   - If a constructor calls a overridable method, surprising results may occur.
     If the parent constructor invoked from child constructor, it may end up
     calling child overriding method while the child obj is not yet constructed.

   - String[] str = new String[10]; => Initializes all 10 strings to be null.
     null instanceof Object is false. So be careful in checking the type.

File name Vs Classes:
   - File could have multiple class'es. public class should match filename.
   - All classes in file A.java (including class A) can be non-public.

Function/Method Declaration/overrides:

   - You can define Private function in child for same func in parent!
     It is just that you won't get overriding effect. 
     Usual access restrictions will apply.

   - You can also define static func in both parent and child.
     This will effectively function hiding not overriding.

   - Overriding child func can relax accessibility -- like from protected to public.
     but not the other way around.
     It is because the child needs to be able to be used in place of parent.

   - f(int) can be called for f('c') function call. char autopromoted to int.
     If there is f(char), that will be preferred to be called.

   - "throws myexception" is part of function signature. If an "unchecked exception"
     is declared to be thrown it is ignored from declaration.

   - Child can not throw any new exception which is not compatible with the
     exceptions thrown by parent.

   - Parent function:  void  f() throws MyException; 
     Child function:   void  f();  ==> It is OK. The child is compatible with parent.
     Child function need not declare all the throws of parent.
     Any runtime exceptions need not be declared as thrown.

   - Child overriding method can freely vary: native, synchronized, final parameter, strictfp.
     They are implementation details and not part of method signature.

   - The fields can only be hidden, not overridden. Same field names are allowed
     in children with any different access modifiers.
     Tip: You can access the parent's field with super keyword.

   - class child extends parent{} 
          super.method() in child will call parent class's method only 
          even if it is overridden method.
          You can use super.super.method() to access any specific method.

What is static class ? 

The class can be declared as : 
   public, protected, (default-package-visibility), private, static
   Top level: only public and default-pkg-level are allowed.
   Note: protected is less restrictive than default.

Only member class can be declared as static. what is the use ?
It can be used as new Outerclss.InnerClass() without using
extra packages. Useful to group classes.

---------------------------------------------------
Nested Classes := static Nested Classes | InnerClasses

static Nested Class = public static member class. Like global class. 
                      Just provides namespace nesting.
      public Class A {   public static Class B { };  }

Types of Innerclasses:

  - Member class: Non-static Nested class member inside a class.

      This is non-static nested classes = inner class:
      This is confusing, so don't use it:
       public Class A {   
          int  i;
          public Class B {  // can also be private.
              int  m = A.this.i;   // Only enclosing class can be referred like this.
          }; 
          public void f() { B myB =  this.new B(); }
      }  

   - Anonymous. e.g
      okButton.addActionListener( new ActionListener(){
        public void actionPerformed(ActionEvent e){
           dispose();
        }
     });

  - Local classes. similar to local variables. no public, protected, etc
    Has access to static & non-static members of enclosing class 
    * as well as* final variables of enclosing block.
    Note: A class defined within a method can only access final fields of 
    the enclosing method; but can access all fields in enclosing class.
    Reason: The local class may outlive the function call.

    Implementation: { class-variables; pointer-to-enclosing-class;
                      pointer-to-final-code-block-variables; }
    good example:
    public static Enumeration walkThrough(final Object[] objs){
       class Enum implements Enumeration{
          ....
          public Object nextElement() { ...; return objs[pos++]; }
       }
       return new Enum();// create new object on the fly.
                         // class definition need not be visible outside
    }


StaticNested := By definition, static member class. Can be public/protected/ etc.

InnerClass := NonstaticMember | Anonymous | Local

NonstaticMember := Non-static member class.
          Class can be declared public/protected/private. (can be accessed from outside)
          Can't declare static var, funcs members

Anonymous := Unnamed Class.
           Can not be declared public/protected or static/nonstatic.
           Can extend static/nonstatic class. (Extending does not influence context)
           Assumes static/non-static depending on context. 
           Can't declare static var, funcs members even in static context.

Local   := Can not be declared public/protected or static/nonstatic.
           Can extend static/nonstatic class. (Extending does not influence context)
           Assumes static/non-static depending on context. 
           Can't declare static var, funcs members even in static context.

Note:   Anonymous and Local Classes assumes static context when defined inside 
        static func or block Else, assumes non-static context.
        i.e. In nonstatic context, the class functions can access instance vars.
        Particular instance of Anon/Local class declaration assumes static/nonstatic
        context at compile time itself.

  - Interface declarations:

    - Any class or interface inside interface is public.
    - Fiedls in an interface are always static and final (and public)
    - All methods in interface are always public and abstract.

    - The methods can't be declared if it has to be static or not.
      Implementing class decides if it should be static or not.

    - Class A implements iface {... Watchout all interface methods must be 
				    declared public here...}

    - Any class inside interface is also static(i.e. defn accessible outside)

       public interface A {  public void f(); 
                 interface X { public void foobar(); }
                 class MyClass { int data = 0; }
                 MyClass  data = new MyClass(); // Common shared dat
                        // it is like static var shared among implementors.
       }

    - Classes and interfaces can be declared inside other classes/interfaces
      either as members or within blocks of code.

  - interface Comparable {  int compareTo(Object o); }
  - interface Comparator {
             int compare(T o1, T o2) ;
             boolean equals(Object obj);
         }
    Note: Default Object.equals() checks only pointer equality.
          If you implement your own compare(), better to override equals().
          Also, see if you have to override hashCode(), since equal objects
          should return equal hash codes.
  - Who uses Comprable, who uses Comparator ?

      SortedSet, SortedMap content elements should implement Comparable, 
      so that the insertion into Set itself can be checked for uniqueness and order.

      The global static java.util sort methods can be used to sort elements whose
      type implement Comparator.
      e.g. Collections.sort(collection, comparator_interface); 
      (note: Collections.sort(collection) will expect the elements to implement Comparable)

  -  interface SortedSet<E> {
      ....
      Comparator<? super E> comparator() ;
          // Returns the comparator associated with this sorted set, 
          // or null if it uses its elements' natural ordering. 
      ...
    }

Serializable :

  - interface Serializable { } -- No functions defined.

  - Class ObjectOutputStream implements object serialization.
    It verifies if the Obj is declared to be "Serializable" then
    executes usual  defaultWriteObject() logic.

  public class ObjectOutputStream
    extends OutputStream
    implements ObjectOutput, ObjectStreamConstants
  {
    public final void writeObject(Object obj)
        throws IOException;

    public void defaultWriteObject()
        throws IOException, NotActiveException;
   Write the non-static and non-transient fields of the current class to this stream. 
   This may only be called from the writeObject method of the class being serialized. 
   It will throw the NotActiveException if it is called otherwise. 
    ...
Why writeObject() and defaultWriteObject() ?
    writeObject() of ObjectOutputStream gives pref to obj.writeObject() if it is defined. 
    defaultWriteObject() blindly writes the obj to stream. 
    Thisway, there is no infinite loop of recursive calls.
    Typically, object's writeObject() calls ObjectOutputStream's defaultWriteObject();

      ...
  }


  - ObjectInputStream implements deserialization :
    public class ObjectInputStream extends InputStream
          implements ObjectInput, ObjectStreamConstants {

      private void readObject(ObjectInputStream stream)
              throws IOException, ClassNotFoundException;

      public  void defaultReadObject()
              throws IOException, ClassNotFoundException;
      ...
    }

  - Synopsis :
    FileOutputStream underlyingStream = new FileOutputStream("C:\\temp\\test");
    ObjectOutputStream serializer = new ObjectOutputStream(underlyingStream);
    serializer.writeObject(serializableObject);

    FileInputStream underlyingStream = new FileInputStream("C:\\temp\\test");
    ObjectInputStream deserializer = new ObjectInputStream(underlyingStream);
    Object deserializedObject = deserializer.readObject( );

  - protected Object resolveObject(Object obj) method (in objectInputStram)
    can return pre-existing object when you read object. 
    e.g. useful to implement singleton class.

  - interface java.io.Externalizable {
         void writeExternal(ObjectOutput stream) throws IOException;
         public void readExternal(ObjectInput stream) throws IOException;
     }
     This interface can be used to completely takeover serializatin/deserialization logic.
     This interface is implemented by the Object itself.

  - For versioning serialization :
    serialver Myclass
    > Myclass: static final long serialVersionUID = 10275539472837495L;
    Include this defn inside your serializable class.

Generics :

// Generic Class :
public class Box<T> {

    private T t;          

    public void add(T t) {
        this.t = t;
    }

    public T get() {
        return t;
    }

    // Generic method
    // Other examples:
    //    public <U extends Number & MyInterface> void inspect(U u)

    public <U> void inspect(U u){
        System.out.println("T: " + t.getClass().getName());
        System.out.println("U: " + u.getClass().getName());
    }

    public static void main(String[] args) {
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.add(new Integer(10));
        integerBox.inspect("some text");
    }
}

Output: T: java.lang.Integer
        U: java.lang.String
  - Generic class:  A<T> and A<T,U> both can not be defined.

  - class A<T> {};  class B extends A {} => then...
           A  = A<Object> ; i.e. You can call generic without type parameter.

  - JDK 6 defines Comparable<T> what about Comparable ?
    That is automatically defined as Comparable<Object> from above defn.
    

-----------------------------------------------------------------
Nested interfaces are always static.
Inner (nonstatic) classes can not have static members.
-----------------------------------------------------------------

Arrays:

   Array extends Object.
   Java Arrays can have non-uniform second dimension:
     int[][] mymatrix = new int[4][4];
         OR
     int[][] mymatrix = new int[4][];
     for (int i=0; i<mymatrix.length; i++) mymatrix[i] = new int[4];
     Note: The second dim could be different than 4 for different rows.

Calling Convention:
   In java, when you pass object, the reference is passed by value.
   Equivalent to passing pointer to Struct in C.
   So, assigning the passed object in a function, does not affect object.

Type Casts: 

   Type casts between types are implicit unless possible loss of precision
   for assignments for primitive types.

   Assignment of child to parent, class to interface, etc are implicit
   and does not require explicit type casting!

   For comparing values, all primitive types are implicitly converted/promoted,
   so there is no warning.

Shift Operator: >> has weird behaviour. int i >> 33 is really i >> 1
     i.e.  33 => 33 mod 32 = 1;

Expression syntax :  a = b = c; is allowed.
           bool b =  a == b && b == c ; is allowed.
           if (i = j) ==> Is not allowed.

Name space: Package name, var name, class, constructor name have separate namespace:

   Following is legal:

    package PackageA; 
    public class classA{ 
       public int classA;  // class and field independent;
       public void PackageA(){}  // pkg, method independent.
       } 
       int  classA(){ return 0; } // constructor and method independent!
    }

    By default, import java.lang.* is included. However, if the local file
    defines a class with same as any java.lang class, then local class takes
    precedence in name resolution.


Transient : Applicable to Field only. Not serialized if declared so.

Volatile:  

       Declaring volatile will force compiler to "read" the reference
       in each iteration of loop, for example.

       Reading the reference may still obtain old value due to cache sync problem,
       hence "synchronized" is still required to sync.

       Atomic read/write of variables is guaranteed by language for all primitive type
       variables except long and double. i.e. It will have value written by some
       thread not inter-mixed.

       If you declare volatile long l, double d => Then atomic read/write will be
       guaranteed for those variables as well.

       A volatile field can not be declared final.

Native method: public native void f(); can not be abstract.

What is java enum type ? added in java 1.5.
It is primitive type -- neither usual "Class" nor "primitive like int".
public enum  Myenum = myenumconst1; i.e. you define an enum class with set
of predefined enum constants defined in it and use it.
It is really a weird type compared to any other type.
Biggest advantage is the toString() representation and typesafe extensions.
If you use INT instead of enum any later redefinition in int value may break
the existing code.

  The important thing to watch out here is serializability of this class
while passing over RMI method parameters and so on. The enum Class should
define readResolve() method so that deserialization does not create
new extraneous class instances for enum.

-----------------------------------------------------------------

What about atomicity of java variable operations ?

  The java operations such as  count++ are guaranteed 
to be atomic as long as the variable is not long or double.
If so, then you must use synchronized to guarantee atomicity.
Else if you declare a primitive variable as volatile,
the atomicity is guaranteed for the operation even if it is long/double

   See java.util.concurrent.locks, java.util.concurrent.atomic
There are AtomicInteger, AtomicLong etc util classes defined to
be able to use these variables in atomic manner.

-----------------------------------------------------------------

logging API loglevel configuration :
  
java -Djava.util.logging.config.file=myLoggingConfigFilePath  ...


- You can hide static method in java, but you can't override.

strictfp Java keyword modifier : Can be applied to class or function.
    public strictfp void f(); Means all float/double calculations will 
    use only float/double intermediate values even if the platform can handle
    more precision. Enforces same behaviour and generation of overflow/underflow
    exceptions uniformly across platforms.

- In java you can write: instancevar.staticFunc(); however it is discouraged:
  write  Classname.staticFunc() instead.



Exceptions:

  - Unchecked Exceptions: Anything that extends RuntimeException or Error

  - Checked Exception : Anything that Extends Exception (other than RuntimeException)
    is checked exception. If it throws just Exception, that is
    checked exception as well.

  - Error extends Throwable

  - RuntimeException extends Exception extends Throwable


Garbage Collection: 
    - System.gc(); 
    - Circular ref of objects does not necessarily prevent garbage collection.
      If the entire circle is not accessible from main prog, it may be garbage collected.

Collections:

   Collection := Set | List
   Set  :=  TreeSet  | HashSet | LinkedHashSet
   List :=  ArrayList | LinkedList

   Set does not contain duplicates. List can.

     HashSet - Best performance. No guaranteed order.
     LinkedHashSet - OK performance. Same order as inserted.
     TreeSet - Ordered based on Comparable nature of elements

     To remove duplicates, do :

     public static <E> Set<E> removeDups(Collection<E> c) {
         return new LinkedHashSet<E>(c);
     }

     Set<String> s = new HashSet<String>();
     if (!s.add(a)) System.out.println("Duplicate detected: " + a);

   TreeSet is sorted.
      SortedSet<StringBuffer> s = new TreeSet<StringBuffer>();
      Above statement throws Error since StringBuffer does not implement Comparable.


   Map  := TreeMap | HashMap | LinkedHashMap

   Map associates setof keys with setof objects. (many to one mapping)
   TreeMap is sorted wrt its keys.

   - Vector is threadsafe. i.e. multiple threads can call v.add(obj), no problems.
   - Hashtable is threadsafe too.
   - HashMap, HashSet, LinkedList are not threadsafe.

   - Vector v=new Vector(); v.add(99); 
     used to not work before java 1.5 because primitive types can't be added.
     Now due to autoboxing/unboxing, this is OK.

java.util.concurrent defines thread safe classes.
   PriorityQueue;
   BlockingQueue Interface implemented by:
      ArrayBlockingQueue; PriorityBlockingQueue; etc

 - PriorityQueue is a queue which implements highest priority element at head
   as provided by user defined Comparator interface passed.
   Can use natural ordering (in case of Integer, etc. )

java.util.Collections class provide useful functions. 
   Note: It is not Collection, it is  "Collections" :
  class java.util.Collections { ...
     public static <T> Collection<T> synchronizedCollection(Collection<T> c);
     ...
  }

Misc Tips:
   - starting /** for comments is identified by javadoc. /* comments ignored.
   - finalize
   - Character literals are like '\u000A' for unicode literals.
   - String literals: non-printable char inside string 
     must use 3-digit octal only.
   - "HelloWorld".substring(1,2) is "e" not "el".
   - StringBuffer :
        StringBuffer buf = new StringBuffer(50); new StringBuffer("Hello");
        buf.append("World"); buf.append('!');
        int cap = buf.capacity(); buf.ensureCapacity(100); 
   - javac A.java will automatically compile B.java as well if A extends B
     and B.class is not present in current dir.
   - JNI method can be declared. The .so needed only at runtime if native invoked.
   - int i; Or: Integer i; System.out.println(i); => OK. from 1.5. 
     println(int) is already defined.
     System.out.println(i + "okay");  => OK! int + str = str + int=>autoboxing in action.
     Autoboxing/unboxing converts int <=>Integer transparently.

   - Typesafe Enum Example :
     enum cafe { 
        BIG ( 10 ) ,
        SMALL ( 1 ),
        MED ( 5 ) ;
        public int mySize = 0;      
        cafe ( int size )
        {
            mySize = size;
        }
     }


java.io :
   -  System.out is java.io.PrintStream; Supports printf(String fmt, Object... args)
   -  System.out.printf("%s", new test()); Prints class's toString() value.

   -  For sprintf, use String.format(fmt, Object ...);   Since 1.5

   -  System.in is java.io.InputStream; No support for scanf.
      Use java.util.Scanner for read functions.   Since 1.5

      Example 1:
      Scanner sc = new Scanner(System.in);
      int i = sc.nextInt();
      String s = sc.nextLine();

      Example 2:
      Scanner sc = new Scanner(new File("myNumbers"));
      while (sc.hasNextLong()) {
          long aLong = sc.nextLong();

  -  For sscanf(), use new Scanner(String s);


Collections Misc:
   -  Map m = new HashMap();
      Object o1 = new Object();
   m.put(o1 , "mill" );
   m.put(o2, "sill" );  // Silently overrides the other
   System.out.println(m.size());

Threads:
    - Dont use Thread.stop() as this can cause corruption.
    - Use class A extends Threads implements Cancelable ;
       Thread1 calls thread2.interrupt(); 
       Thread2:  while (!interrupted()) do_some_work;

   - If you divide by zero, and don't catch it, only that thread is
     terminated. If you have other threads, it will continue program.

   - Thread.dumpStack() prints stack trace to System.out


Thread Groups:
   - Can have name.  Useful in debugging
   - Could be hierarchical.
   - Can assign security constraints for group.
   - Thread group's uncaughtException() handler called just before thread death.
     
Operator precedence and associativity:
  Following order of precedence apply:
 - postfix : e.g. [] . ++ -- ; e.g. 
 - unary : ++expr, ~, !;  e.g. ++ expr[0]; ! bool1 && bool2 
 - creation and cast : new  (type)expr
 - Multiplication : * / %
 - Addition : + -
 - Shift  :  << >>  >>>
 - relational :  <  > <= >= instanceof
 - equality : ==  !=
 -  ^ |  && ||  ?:  =  += *= etc.

 Binary operators left associatie except assignment.
 conditional operator ?: is right associative.

 - i= 3;  
    i++ + i++ + --i := 3 + 4 + 4 is 11

Control Statements:
  -label: statement ;
  - break;  -- breaks innermost loop
  - break label; -- breaks the loop of stmt as labeled.
  - continue; -- next loop for innermost loop.
  - continue label; -- next for loop of stmt as labeled.
  - No goto.

Locale, Encoding, Unicode :

  - get platform locale from : Locale.getDefault() => returns "en" or "en_US"

  - String(byte[] bytes, String charsetName) => constructs String using 
    array of raw bytes using specified encoding.

  - String(byte[] bytes, Charset charset) 

  - import java.nio.charset.Charset;
     CharSet stands for (encoding scheme, character sets). Has canonical names and aliases. 

  - A "coded character set" is a mapping between abstract character and integer.
    (and a definition of what is upper, lower case etc.) 
    This generally has 1:1 relation with Locale

  - A character-encoding scheme is a mapping between a coded character set and a set of 
    octet (eight-bit byte) sequences.  e.g. UTF-16, EUC etc.

  - Following encoding suported by all JVMs :

   US-ASCII   Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the Unicode 
   ISO-8859-1 ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1 
   UTF-8      Eight-bit UCS Transformation Format 
   UTF-16BE   Sixteen-bit UCS Transformation Format, big-endian byte order 
   UTF-16LE   Sixteen-bit UCS Transformation Format, little-endian byte order 
   UTF-16     Sixteen-bit UCS Transformation Format, byte order identified by an optional 
              byte-order mark 

  - Typically one encoding scheme can support multiple character sets.
    Some encodings are fixed associated with only one charset.
    For US-ASCII, the encoding scheme and character set are same.
    UTF-8 used to encode only unicode. 
    EUC can encode many asian languages.

  - The native character encoding of the Java programming language is UTF-16. 
    A charset in the Java platform therefore defines a mapping between sequences 
    of sixteen-bit UTF-16 code units and sequences of bytes. 

  - Charset.defaultCharset()  ==> returns  "US-ASCII" on my machine.
    If I set my locale to  iso_8859_1, then JVM calls return:
      The default locale is: en_8859_1
      The default charset is: ISO-8859-1

  - Note: Java Charset is both character set and encoding scheme.
    Hence UTF-16 is used to encode Unicode, which in turn, can encode so many different
    real character sets. i.e. Many world languages have charset defn which is designed to 
    be non-conflicting subset of unicode.

  - Java program source can be in unicode. Hence java identifier, constants can be 
    unicode characters. (The .java file should be in UTF-8 encoding?)


How to make an object cloneable ? 
/** This is how you make an object Cloneable
 *  Object.clone() is protected. Now make it public.
 *  The clone() method is special - it does the job if
 *  the obj is declared to implement Cloneable.
 */
   public class A implements Cloneable {

      public Object clone() throws CloneNotSupportedException {
         return super.clone();
      }
   }

Section 1: Declarations, Initialization and Scoping 
    - Varargs
    public void drawPolygon (Point... points) {
        // access points[0], points[1], etc. points.length could be zero
        // if user has not passed anyargs.
    }

    - Java methods don't support static local variables even if the method is static!
      Note: In C/C++ it is supported.

    -  int  myarr[10];  ==> Is invalid statement in Java!!!
       It should be:  int myarr[] = new int[10]; // or new int[0]

    -  int $var = 10;  ==> Is allowed in java!
    -  Number is abstract super class for Integer, double, AtomicInteger, etc.
    -  AtomicInteger class provides compareAndSet() etc operations.

    -  Method local variable should be initialized before access.
       whereas class member variable need not be!!!

    -  char c = 10; int i = 20;  c += i; => OK;  c = c + i; => Compile Error!!!
       (c + i) becomes int, and there is loss of precision when you assign it to c.

    -  byte and char are not implicit type compatible. They need explicit type casting.
    -  Unreachable statement is error, not warning.

    -  A method can't be declared abstract & static

Generics : 

    -  Generic class Box<T> defines Box<Object> at runtime. But useful during
       compile time to check strict type checking.

    -  Box<String> box; String s = box.get(0); does not need type casting!
       box.add(10) will complain that 10 is not string!
       Autoboxing does not help here!!! why ? 
       Autoboxing only auto converts between int/Integer. Not from int to String.

    -  Generic method can express one type in terms of other type in func parameter:
    -  class Box<T> {

         private T t;                  
         static int  total;

    // T is not available as runtime type. So "t instanceof T" check is not allowed.
    //        T  t = new T();   ==> Not allowed!
    //        T  t = (T) x ;    ==> OK! but you can call only Object's method like wait()
    //                                  Actually it internally type casts to Object.     
    //     Comparable c = (Comparable) x; ==>  OK. Runtime exception, if you had passed
    //                           Non Comparable object to the method.
    //

         public void add(T t) { this.t = t; }

         public T get() { return t; }

         // Generic method can express one type as a relative function of other.
         public static <U> void TotalCount(U u, List<U> list){ total ++; }
         // Calling this function is: 
         //       box.<Integer>TotalCount(10, list);  // OR ...
         //       box.TotalCount(10, list); // Compiler will match with "Type Inference"

        public <X> List<X> mymethod(List<?> type){
            System.out.println(" type is " + type);
            // Following stmt is Error! because you can typecast unknown type to known;
            // but not the other way around.
            return new ArrayList<String>();  // Error! 
            return new (List<X>) ArrayList<String>();  //  OK!!!
        }
      }

    - Bounded types : 

        Box<T extends Number> { ... }

        public <U extends Number> void inspect(U u){
            System.out.println("U: " + u.getClass().getName());
        }

        public <U extends Number & MyInterface > void inspect(U u){}

        "extends" keyword used for both extending classes or implementing interfaces.

    - Box<Number>  numbox =  new Box<Integer>(); is not type compatible.
      Though Integer is subtype of NUmber. You have to typecast.

    - // Use of wild card

      public static  void example(Box<? extends Number>  b){
         Box<? extends Number>  box = b; // OK. But Can't call box.add(new Integer(10))
         // Box<?>              box = b; // OK. Same restrictions like above.
         Box                  mybox = b; // OK. mybox.get() will return Object
      }

    - Box<? super Integer>  box = new Box<Integer>(); => OK. It means Integer or super
      Box<? super Child>  box = new Box<Parent>(); => OK if Parent is one of the super
                              classes of Child. Still only Object methods can be invoked
                              from box. e.g. box.wait();

      List<String>  list  = new ArrayList();  => OK!!! with a warning
      List<String>  list  = new ArrayList<Object>(); => Compile time error!!!

    - For backward compatibility or whatever reason,  new ArrayList() can be
      passed to the function which accepts:  List<String> !
      However, if you start using <> then strict type checking enforced at 
      compile time!

    If you need type compatibility with generics use ? with extends/super keywords :
    - Comparator<Integer> is not type compatible with Comparator<Number>
      Comparator<? extends Number> is type compatible with Comparator<Number>
      Comparator<Integer> is type compatible with Comparator<? super Integer>

    - Note: Using "Box<?> b; "  and " Box b;" are equivalent but for the following diff:

      * Box<?> b; b.add(obj) => Not OK; 
        since at compile time, it wants to know what object type T (in void add(T obj))
        being passed.
      * Box b; b.add(obj); => is accepted, since obj assumed to be Object.

      However,  b.add(obj) can not be called with Box<?> since the parameter type
      can not be inferred correctly. 
      In general, you should use Box<?> whenever possible as it captures max compile time 
      errors. 

    - Type Erasure: Runtime does not have exact type info :
        E item2 = new E();   //Compiler error
        E[] iArray = new E[10]; //Compiler error
        E obj = (E)new Object(); //Unchecked cast warning

    - Generics are extends'ible.
         public interface Collection<E> extends Iterable<E> { 
             ....
             <T> T[] toArray(T[] a);   // Generic Method!!!
             // Just expresses that the first arg should be Array type and
             // return type is also same!
         }

 
SCJP Exam Objectives:

Section 1: Declarations, Initialization and Scoping 

--------------------------------------------------------------------------------


Develop code that declares classes (including abstract and all forms of nested classes), interfaces, and enums, and includes the appropriate use of package and import statements (including static imports). 
Develop code that declares an interface. Develop code that implements or extends one or more interfaces. Develop code that declares an abstract class. Develop code that extends an abstract class. 
Develop code that declares, initializes, and uses primitives, arrays, enums, and objects as static, instance, and local variables. Also, use legal identifiers for variable names. 
Develop code that declares both static and non-static methods, and - if appropriate - use method names that adhere to the JavaBeans naming standards. Also develop code that declares and uses a variable-length argument list. 
Given a code example, determine if a method is correctly overriding or overloading another method, and identify legal return values (including covariant returns), for the method. 
Given a set of classes and superclasses, develop constructors for one or more of the classes. Given a class declaration, determine if a default constructor will be created, and if so, determine the behavior of that constructor. Given a nested or non-nested class listing, write code to instantiate the class. 


Section 2: Flow Control 

--------------------------------------------------------------------------------


Develop code that implements an if or switch statement; and identify legal argument types for these statements. 
Develop code that implements all forms of loops and iterators, including the use of for, the enhanced for loop (for-each), do, while, labels, break, and continue; and explain the values taken by loop counter variables during and after loop execution. 
Develop code that makes use of assertions, and distinguish appropriate from inappropriate uses of assertions. 
Develop code that makes use of exceptions and exception handling clauses (try, catch, finally), and declares methods and overriding methods that throw exceptions. 
Recognize the effect of an exception arising at a specified point in a code fragment. Note that the exception may be a runtime exception, a checked exception, or an error. 
Recognize situations that will result in any of the following being thrown: ArrayIndexOutOfBoundsException,ClassCastException, IllegalArgumentException, IllegalStateException, NullPointerException, NumberFormatException, AssertionError, ExceptionInInitializerError, StackOverflowError or NoClassDefFoundError. Understand which of these are thrown by the virtual machine and recognize situations in which others should be thrown programatically. 


Section 3: API Contents 

--------------------------------------------------------------------------------


Develop code that uses the primitive wrapper classes (such as Boolean, Character, Double, Integer, etc.), and/or autoboxing & unboxing. Discuss the differences between the String, StringBuilder, and StringBuffer classes. 
Given a scenario involving navigating file systems, reading from files, or writing to files, develop the correct solution using the following classes (sometimes in combination), from java.io: BufferedReader,BufferedWriter, File, FileReader, FileWriter and PrintWriter. 
Develop code that serializes and/or de-serializes objects using the following APIs from java.io: DataInputStream, DataOutputStream, FileInputStream, FileOutputStream, ObjectInputStream, ObjectOutputStream and Serializable. 
Use standard J2SE APIs in the java.text package to correctly format or parse dates, numbers, and currency values for a specific locale; and, given a scenario, determine the appropriate methods to use if you want to use the default locale or a specific locale. Describe the purpose and use of the java.util.Locale class. 
Write code that uses standard J2SE APIs in the java.util and java.util.regex packages to format or parse strings or streams. For strings, write code that uses the Pattern and Matcher classes and the String.split method. Recognize and use regular expression patterns for matching (limited to: . (dot), * (star), + (plus), ?, \d, \s, \w, [], ()). The use of *, +, and ? will be limited to greedy quantifiers, and the parenthesis operator will only be used as a grouping mechanism, not for capturing content during matching. For streams, write code using the Formatter and Scanner classes and the PrintWriter.format/printf methods. Recognize and use formatting parameters (limited to: %b, %c, %d, %f, %s) in format strings. 


Section 4: Concurrency 

--------------------------------------------------------------------------------


Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable. 
Recognize the states in which a thread can exist, and identify ways in which a thread can transition from one state to another. 
Given a scenario, write code that makes appropriate use of object locking to protect static or instance variables from concurrent access problems. 
Given a scenario, write code that makes appropriate use of wait, notify, or notifyAll. 


Section 5: OO Concepts 

--------------------------------------------------------------------------------


Develop code that implements tight encapsulation, loose coupling, and high cohesion in classes, and describe the benefits. 
Given a scenario, develop code that demonstrates the use of polymorphism. Further, determine when casting will be necessary and recognize compiler vs. runtime errors related to object reference casting. 
Explain the effect of modifiers on inheritance with respect to constructors, instance or static variables, and instance or static methods. 
Given a scenario, develop code that declares and/or invokes overridden or overloaded methods and code that declares and/or invokes superclass or overloaded constructors. 
Develop code that implements "is-a" and/or "has-a" relationships. 


Section 6: Collections / Generics 

--------------------------------------------------------------------------------


Given a design scenario, determine which collection classes and/or interfaces should be used to properly implement that design, including the use of the Comparable interface. 
Distinguish between correct and incorrect overrides of corresponding hashCode and equals methods, and explain the difference between == and the equals method. 
Write code that uses the generic versions of the Collections API, in particular, the Set, List, and Map interfaces and implementation classes. Recognize the limitations of the non-generic Collections API and how to refactor code to use the generic versions. 
Develop code that makes proper use of type parameters in class/interface declarations, instance variables, method arguments, and return types; and write generic methods or methods that make use of wildcard types and understand the similarities and differences between these two approaches. 
Use capabilities in the java.util package to write code to manipulate a list by sorting, performing a binary search, or converting the list to an array. Use capabilities in the java.util package to write code to manipulate an array by sorting, performing a binary search, or converting the array to a list. Use the java.util.Comparator and java.lang.Comparable interfaces to affect the sorting of lists and arrays. Furthermore, recognize the effect of the "natural ordering" of primitive wrapper classes and java.lang.String on sorting. 


Section 7: Fundamentals 

--------------------------------------------------------------------------------


Given a code example and a scenario, write code that uses the appropriate access modifiers, package declarations, and import statements to interact with (through access or inheritance) the code in the example. 
Given an example of a class and a command-line, determine the expected runtime behavior. 
Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters. 
Given a code example, recognize the point at which an object becomes eligible for garbage collection, and determine what is and is not guaranteed by the garbage collection system. Recognize the behaviors of System.gc and finalization. 
Given the fully-qualified name of a class that is deployed inside and/or outside a JAR file, construct the appropriate directory structure for that class. Given a code example and a classpath, determine whether the classpath will allow the code to compile successfully. 
Write code that correctly applies the appropriate operators including assignment operators (limited to: =, +=, -=), arithmetic operators (limited to: +, -, *, /, %, ++, --), relational operators (limited to: <, <=, >, >=, ==, !=), the instanceof operator, logical operators (limited to: &, |, ^, !, &&, ||), and the conditional operator ( ? : ), to produce a desired result. Write code that determines the equality of two objects or two primitives. 



