Thursday, July 28, 2011

Increasing the quality of source code

In programing there are some techniques for that:
Peer reviews
Software inspections

I prefer to work somewhere where this processes are use to do.

Tuesday, June 21, 2011

Kickstart jUnit 4 example

First steps in jUnit.

import org.junit.*;
import static org.junit.Assert.*;


/**
*
* @author Georgi Mitev
*/
public class XTest {

    @Before
    // Will be performed before each test.
    public void testSetup(){
        System.out.println("Setup for test complete.");
    }

    @After
    // Will be performed after each test.
    public void testComplete() {
        System.out.println("Test complete.");
    }

    @Test
    public void test1() {
        System.out.println("Starting test 1.");
        assertTrue( true ) ;
    }

    @Test
    public void test2(){
        System.out.println("Starting test 2.");
        assertTrue( true ) ;
    }
}


We could call it easy with maven command


    • mvn test
      mvn test -Dsurefire.useFile=false - outputs more information about the errors.

  • The output of the program is:

    Running XTest
    Setup for test complete.
    Starting test 1.
    Test complete.
    Setup for test complete.
    Starting test 2.
    Test complete.
    Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.062 sec

    Results :

    Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

    The maven configuration for junit is
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <!--version>3.8.1</version-->
          <version>4.8.1</version>
          <scope>test</scope>
        </dependency>
        ...
      </dependencies>
    
    

    jUnit classes are placed in [project-home]\src\test\java\[junit package]\[junit class]

    Tuesday, April 26, 2011

    Database Normalization

    Database Normalization is the process of efficiently organizing data in a database. There are two goals of the normalization process:
    * eliminating redundant data (for example, storing the same data in more than one table)
    * ensuring data dependencies make sense (only storing related data in a table).

    Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.

    The Normal Forms

    The database community has developed a series of guidelines for ensuring that databases are normalized. These are referred to as normal forms and are numbered from one (the lowest form of normalization, referred to as first normal form or 1NF) through five (fifth normal form or 5NF). In practical applications, you'll often see 1NF, 2NF, and 3NF along with the occasional 4NF.

    First Normal Form (1NF)

    First normal form (1NF) sets the very basic rules for an organized database:
    * Eliminate duplicative columns from the same table.
    * Create separate tables for each group of related data and identify each row with a unique column or set of columns (the primary key).

    Second Normal Form (2NF)

    Second normal form (2NF) further addresses the concept of removing duplicative data:
    * Meet all the requirements of the first normal form.
    * Remove subsets of data that apply to multiple rows of a table and place them in separate tables.
    * Create relationships between these new tables and their predecessors through the use of foreign keys.

    Third Normal Form (3NF)

    Third normal form (3NF) goes one large step further:
    * Meet all the requirements of the second normal form.
    * Remove columns that are not dependent upon the primary key.

    Fourth Normal Form (4NF)

    Finally, fourth normal form (4NF) has one additional requirement:
    * Meet all the requirements of the third normal form.
    * A relation is in 4NF if it has no multi-valued dependencies.

    Remember, these normalization guidelines are cumulative. For a database to be in 2NF, it must first fulfill all the criteria of a 1NF database.

    If you'd like to ensure your database is normalized, explore our other articles in this series:

    * Database Normalization Basics
    * Putting your Database in First Normal Form
    * Putting your Database in Second Normal Form
    * Putting your Database in Third Normal Form

    Thursday, April 7, 2011

    Spring by examples

    A nice to have link for for helping Spring developers get started with different Spring projects:
    http://www.springbyexample.org/

    Wednesday, April 6, 2011

    Java portlets

    Portlets are pluggable user interface software components that are displayed in a web portal. For example, a portlet may be a page element showing the wether forecast.

    Note how the portlet occupies only a part of the portal page. This is the primary difference between a portlet and a servlet. A portlet is meant to occupy only a part of the web page. And a portal web page consists of multiple, different portlets.

    A number of vendors provide commercial implementations of the portlet container. Some of the leading vendors are IBM, Oracle, Vignette Corporation, JBoss, and Software AG. These vendors provide standards-based implementations as well as extensions not yet approved by the standards body. In addition, a number of open-source portal solutions support JSR168, such as Apache's Jetspeed-2 Enterprise Portal

    Tuesday, April 5, 2011

    Java volatile

    volatile keyword is used to indicate that a variable's value will be modified by different threads.

    Declaring a volatile Java variable means:
    • The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory";
    • Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.

    We say "acts as though" in the second point, because to the programmer at least (and probably in most JVM implementations) there is no actual lock object involved. Here is how synchronized and volatile compare:

    Difference between synchronized and volatile

    Characteristic Synchronized Volatile
    Type of variable Object Object or primitive
    Null allowed? No Yes
    Can block? Yes No
    All cached variables synchronized on access? Yes From Java 5 onwards
    When synchronization happens When you explicitly enter/exit a synchronized block Whenever a volatile variable is accessed.
    Can be used to combined several operations into an atomic operation Yes Pre-Java 5, no. Atomic get-set of volatiles possible in Java 5.



    An example:
    public class StoppableTask extends Thread {
      private volatile boolean stopThread;
    
      public void run() {
        while( !stopThread ) {
          // do something
        }
      }
    
      public void stopMe() {
        stopThread = true;
      }
    } 
     

    Monday, April 4, 2011

    Java threads

    Important methods
    * constructior Thread( ThreadGroup group, Runnable target, String name ) - If the target argument is null, this thread's run method is called when this thread is started.
    * static int enumerate( Thread[] tarray ) - Copies into the specified array every active thread in the current thread's thread group and its subgroups.
    * int getPriority();* join() - Waits for this thread to die.
    * join( long millis ) - Waits at most millis milliseconds for this thread to die.
    * run() - If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
    * setDaemon( boolean on ) - Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the thread is started.
    * sleep(long millis) throws InterruptedException - Causes the currently executing thread to sleep (temporarily cease execution). If any thread has interrupted the current thread, InterruptedException exception is thrown.
    * start() - Causes this thread to begin execution. The result is that two threads are running concurrently.
    * run() - If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
    * stop() - Deprecated!
    * interrupt() - If this thread is blocked in an invocation of the wait(), wait(long), or wait(long, int) methods of the Object class, or of the join(), join(long), join(long, int), sleep(long), or sleep(long, int), methods of this class, then its interrupt status will be cleared and it will receive an InterruptedException.
    * suspend() - Deprecated!
    *

    The deprecated way:
        private Thread blinker;
    
        public void start() {
            blinker = new Thread(this);
            blinker.start();
        }
    
        public void stop() {
            blinker.stop();  // UNSAFE!
        }
    
        public void run() {
            Thread thisThread = Thread.currentThread();
            while (true) {
                try {
                    thisThread.sleep(interval);
                } catch (InterruptedException e){
                }
                repaint();
            }
        }
    

    The correct way:
        private volatile Thread blinker;
    
        public void stop() {
            blinker = null;
        }
    
        public void run() {
            Thread thisThread = Thread.currentThread();
            while (blinker == thisThread) {
                try {
                    thisThread.sleep(interval);
                } catch (InterruptedException e){
                }
                repaint();
            }
        } 
     
    There are two ways to create a new thread of execution.
    The first one is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.
    In all cases, the tread is started with run() method.

    Sunday, April 3, 2011

    Java API for XML Processing (JAXP)

    The Java API for XML Processing, or JAXP, is one of the Java XML programming APIs. It provides the capability of validating and parsing XML documents. The three basic parsing interfaces are:
    * the Document Object Model parsing interface or DOM interface
    * the Simple API for XML parsing interface or SAX interface
    * the Streaming API for XML or StAX interface (part of JDK 6; separate jar available for JDK 5)

    In addition to the parsing interfaces, the API provides an XSLT interface to provide data and structural transformations on an XML document.

    DOM interface
    DOM model parses an entire XML document and constructs a complete in-memory representation of the document. The created objects are from package e org.w3c.dom.

    SAX interface
    The SAX parser is called the SAXParser and is created by the javax.xml.parsers.SAXParserFactory. Unlike the DOM parser, the SAX parser does not create an in-memory representation of the XML document and so is faster and uses less memory. Instead, the SAX parser informs clients of the XML document structure by invoking callbacks, that is, by invoking methods on a org.xml.sax.helpers.DefaultHandler instance provided to the parser.

    The DefaultHandler class implements these interfaces:
    * ContentHandler
    * DTDHandler
    * EntityResolver
    * ErrorHandler

    StAX interface
    StAX was designed as a median between the DOM and SAX interface. In its metaphor, the programmatic entry point is a cursor that represents a point within the document. The application moves the cursor forward - 'pulling' the information from the parser as it needs.

    XSLT interface
    It allows applying transformations (XSL transformations) to XML files

    Wednesday, March 30, 2011

    Java Transient Variables

    If you mark an instance variable as transient, you're telling the JVM to skip (ignore) this variable when you attempt to serialize the object containing it. Serialization is one of the coolest features of Java; it lets you save an object by writing its state to the serialisation stream.

    Java Instance variables and Class variables

    aka static/non-static variables.

    In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each object of the class has a separate copy. They live in memory for the life of the class.

    An instance variable is the opposite of class variable, and it is a special type of instance member.

    A class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist. We use keyword static for declaring class variables.

    Instance variable:
    ■ Can be marked final
    ■ Can be marked transient
    ■ Cannot be marked abstract
    ■ Cannot be marked synchronized
    ■ Cannot be marked strictfp
    ■ Cannot be marked native
    ■ Cannot be marked static, because then they'd become class variables.

    Java default values

    There is a simple rule - when you define a member variable, it gets a default value. When you define local value, it do not get any default value - it has to be inicialized before the first use, or an compile-time exception will be thrown.

    Default values for member variables:

    Data Type Default Value (for fields)
    byte 0
    short 0
    int 0
    long 0L
    float 0.0f
    double 0.0d
    char '\u0000'
    Any object null
    boolean false

    Java constructors

    Here are some legal and illegal examples:

    class ConstructorExamples {
        // legal constructors
        ConstructorExamples () { }
        private ConstructorExamples (byte b) { }
        ConstructorExamples (int x) { }
        ConstructorExamples (int x, int... y) { }
    
        // illegal constructors
        void ConstructorExamples () { }           // it's a method, not a constructor
        ConstructorLike () { }                    // not a method nor a constructor
        ConstructorExamples (short s);            // looks like an abstract method
        static ConstructorExamples (float f) { }  // can't be static
        final ConstructorExamples (long x) { }    // can't be final
        abstract ConstructorExamples (char c) { } // can't be abstract
        ConstructorExamples (int... x, int t) { } // bad var-arg syntax
    }
    

    Java Methods with Variable Argument Lists, var-args

    As of 5.0, Java allows you to create methods that can take a variable number of
    arguments. This feature is also known as "var-args", "varargs", "variable-length argument lists" or "variable arguments,".

    Var-args declarations
    Here are some legal and illegal var-arg declarations:

    Legal:
    void myMethodX( int... a ) { } // expects from 0 to many ints
                                 // as parameters
    void myMethodY( char c, int... a ) { } // expects first a char,
                                         // then 0 to many ints
    void myMethodZ( Animal... animal ) { } // 0 to many Animals
    void myMethodXYZ( Object... anyKindOfObjects ) { } 
                                // 0 to many Objects
    

    Illegal:
    void myMethodA( int x... ) { }              // illegal syntax
    void myMethodB( String... str, byte b ) { } // var-arg must be last
    void myMethodC( int... x, char... y ) { }   // too many var-args
    

    Accessing var-args
    Example 1:
        public static void test(int some, String... args) {
            System.out.print("\n" + some);
            for(String arg: args) {
                System.out.print(", " + arg);
            }
        }
    


    Example 2:
    static int sum (int ... numbers)
    {
       int total = 0;
       for (int i = 0; i < numbers.length; i++)
            total += numbers [i];
       return total;
    }
    

    Java HttpServletResponse

    HttpServletResponse is an interface from package javax.servlet.http. It extends javax.servlet.ServletResponse.

    The important interface members are:
    * addCookie(Cookie cookie);
    * addHeader(String name, String value);
    * sendError(int sc) Sends an error response to the client using the specified status code and clearing the buffer;
    * sendError(int sc, String msg) Sends an error response to the client using the specified status.
    * sendRedirect( String newLocation ) throws IOException - Sends a temporary redirect response to the client using the specified redirect location URL. Realised by http code 302 (Redirect).
    * setHeader(String name, String value);
    * setStatus(int sc) Sets the status code for this response.

    Noticable methods from the super interface javax.servlet.ServletResponse:
    * String getCharacterEncoding();
    * String getContentType() - Returns the content type used for the MIME body;
    * boolean isCommitted();
    * setCharacterEncoding(String charset);
    * setContentType(String type);

    Tuesday, March 29, 2011

    Java ServletContext

    ServletContext is an interface from package javax.servlet;

    Getting ServletContext
    ServletContext could be get by session.getServletContext() method.
    HttpSession could be get by request.getSession( boolean create );

    The most important members are:
    * addFilter(java.lang.String filterName, Filter filter) - Registers the given filter instance with this ServletContext under the given filterName;
    * addListener(java.lang.Class listenerClass) - Adds a listener of the given class type to this ServletContext;
    * Object getAttribute(java.lang.String name);
    * ClassLoader getClassLoader();
    * String getContextPath();
    * getMimeType(java.lang.String file);
    * log( String message, Throwable throwable );
    * setAttribute( String name, java.lang.Object object );

    Java HttpSession

    HttpSession is interface from package javax.servlet.http.

    Getting HttpSession
    A HttpSession object could be get by request.getSession( boolean create );

    The most important methods are:
    * Object getAttribute(java.lang.String name);
    * Enumeration getAttributeNames();
    * long getCreationTime();
    * long getLastAccessedTime();
    * ServletContext getServletContext();
    * invalidate();
    * removeAttribute(java.lang.String name);
    * setAttribute( String name, Object value );
    * setMaxInactiveInterval(int interval) - Specifies the time, in seconds;
    *

    java HttpRequest

    The interface HttpRequest is located in package javax.servlet.http.

    Here are some important members:
    * Cookie[] getCookies()
    * String getHeader(java.lang.String name) - Returns the value of the specified request header as a String
    * String getMethod() - GET, POST, or PUT
    * String getQueryString() - Returns the query string that is contained in the request URL after the path.
    * String getRemoteUser() - Returns the login of the user making this request, if the user has been authenticated;
    * String getRequestURI() - Returns the part of this request's URL from the protocol name up to the query string;
    * StringBuffer getRequestURL() - Reconstructs the URL the client used to make the request;
    * HttpSession getSession( boolean create );
    * boolean isUserInRole( String role );

    ----
    And some inherited from javax.servlet.http.Request:
    * Object getAttribute( String name );
    * Enumeration getAttributeNames();
    * String getContentType() - Returns the MIME type of the body of the request;
    * String getParameter( String name );
    * Enumeration getParameterNames();
    * String getServerName();
    * int getServerPort();
    * String getRemoteHost() - Returns the fully qualified name of the client ( or the last proxy that sent the request);
    * setAttribute( String name, Object o);
    * removeAttribute(java.lang.String name);
    * Locale getLocale();

    Java Native Interface

    Java Native Methods

    The native modifier indicates that a method is implemented in platform-dependent code, often in C / C++. Native is a modifier and a reserved keyword and that native can be applied only to methods. Note that a native method's body must be a semicolon (;) (like abstract methods), indicating that the implementation is omitted.

    Pros and cons
    The ability to write just one set of code in Java and have it run on every system with a Java run-time is one of Java's primary strengths. But this platform independence has one key drawback: What do we do with the vast amount of existing code? The trick is to use the so-called native method interface (JNI).

    Writing native methods involves importing code from other programming language (eg. C code) into your Java application.

    Step-by-step guide
    In the example we will use C language and linux/unix host platform. The steps are:
    * Write Java code
    * Compile Java code
    * Create C header (.h file)
    * Create C stubs file
    * Write C code
    * Create shared code library (or DLL)
    * Run application

    Example Java code
    class JavaPrinter {
        public native void printText();
        static
        {
           System.loadLibrary( "nativeprinter" );   
               // Attention: Note lowercase of library name
        }
    
        public static void main (String[] args) {
           JavaPrinter p = new JavaPrinter();
           p.printText();
        }
    }
    

    Compile the Java code
    javac JavaPrinter.java
    

    Create a C header file
    javah JavaPrinter
    

    Create a C source file
    javah -stubs JavaPrinter
    

    Add C/C++ code
    Now, let's write the actual code to print out our greeting. By convention we put this code in a file named after our Java class with the string "Imp" appended to it. This results in JavaPrinterImp.c. Place the following into JavaPrinterImp.c:
    #include   // Standard native method stuff.
    #include "JavaPrinter.h"   // Generated before.
    #include          // Standard C IO
    void JavaPrinter_printText (struct HJavaPrinter *this) {
        puts ("Hi from C language!!!");
    } 
    

    Create a shared library
    This is for GCC compiler. First, compile the C source files that we have already created. You have to tell the compiler where to find the Java native method support files, but the main trick here is that you have to explicitly tell the compiler to produce Position Independent Code (PIC):

    gcc -I/usr/local/java/include -I/usr/local/java/include/genunix -fPIC -c JavaPrinter.c JavaPrinterImp.c
    

    ow, create a shared library out of the resulting object (.o) files with the following magical incantation:

    gcc -shared -Wl,-soname,libnativeprinter.so.1 
    -o libnativeprinter.so.1.0 JavaPrinter.o JavaPrinter.o
    

    Copy the shared library file to the standard short name:

    cp libnativeprinter.so.1.0 libnativeprinter.so
    

    JNI notes:
    * subtle errors in the use of JNI can destabilize the entire JVM in ways that are very difficult to reproduce and debug.
    * only applications and signed applets can invoke JNI.
    * an application that relies on JNI loses the platform portability Java offers.
    * the JNI framework does not provide any automatic garbage collection for non-JVM memory resources allocated by code executing on the native side. Consequently, native side code must assume the responsibility for explicitly releasing any such memory resources that it itself acquires.
    * error checking is a MUST or it has the potential to crash the JNI side and the JVM.

    Monday, March 28, 2011

    Java Reentrant Synchronization

    Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block.

    Java Synchronized Statements

    Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

        public void addName(String name) {
            synchronized(this) {
                lastName = name;
                nameCount++;
            }
            nameList.add(name);
        }
    

    In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.

    Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, class MsLunch has two instance fields, c1 and c2, that are never used together. All updates of these fields must be synchronized, but there's no reason to prevent an update of c1 from being interleaved with an update of c2 — and doing so reduces concurrency by creating unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associated with this, we create two objects solely to provide locks.

        public class MsLunch {
            private long c1 = 0;
            private long c2 = 0;
            private Object lock1 = new Object();
            private Object lock2 = new Object();
    
            public void inc1() {
                synchronized(lock1) {
                    c1++;
                }
            }
    
            public void inc2() {
                synchronized(lock2) {
                    c2++;
                }
            }
        }
    

    Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields.

    Java syncronized methods

    The synchronized keyword indicates that a method can be accessed by only one
    thread at a time.

    public synchronized BagContainer readBag( int bagId ) {
    // do getting of object
    }

    When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. The lock release occurs even if the return was caused by an uncaught exception.

    You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

    Java abstract methods

    An abstract method is a method that's been declared as abstract but not implemented, so, the method contains no functional code.

    It is illegal to have an abstract method in a class that is not explicitly declared abstract.

    The first concrete subclass of an abstract class must implement all abstract methods of the superclass.

    Abstract and static modifiers are NOT allowed. The compiler will output such error:

    SomeClass.java:37: illegal combination of modifiers: abstract and
    static
    abstract static void doMethod();

    Java final methods

    The final keyword prevents a method from being overridden in a subclass, and is
    often used to enforce the API functionality of a method.

    class SomeClass{
    public final void finalMethod() {
    System.out.println("One thing.");
    }
    }

    It's legal to extend SuperClass, since the class isn't marked final, but we can't
    override the final method finalMethod()

    Java interface constants

    All interface constants are "public static final", no matter they are daclared this way or not.

    Java strictfp keyword

    strictfp is a keyword in the Java programming language that restricts floating-point calculations to ensure portability. Using strictfp guarantees that results of floating-point calculations are identical on all platforms. It was introduced into version 1.2.

    Just an example: x86 processors support 80 bit double values. This type is used for intermidiate opetations in Java, to avoid buffer overflows and underflows. The result value is stored according IEEE 754 standard, as 64 bit double. This is when we do not use strictfp keyword.

    When we add strictfp, intermidiate java calculations are also reduced to 64 bits. The chance for underflows/overflows is greater but we keep the the results will be compatible with results in Java 1.1.

    Usage
    strictfp can be used on classes, interfaces and non-abstract methods. When applied to a method, it causes all calculations inside the method to use strict floating-point math. When applied to a class, all calculations inside the class use strict floating-point math.

    Java interfeces

    Some rules about java interfeces:
    ■ All interface methods are implicitly public and abstract. In other words, you do not need to actually type the public or abstract modifiers in the method declaration, but the method is still always public and abstract.
    ■ All variables defined in an interface must be public, static, and final — in other words, interfaces can declare only constants, not instance variables. Interface methods must not be static.
    ■ Because interface methods are abstract, they cannot be marked final, strictfp, or native. (More on these modifiers later.)
    ■ An interface can extend one or more other interfaces.
    ■ An interface cannot extend anything but another interface.
    ■ An interface cannot implement another interface or class.
    ■ Interface types can be used polymorphically.

    Java Final Classes

    When used in a class declaration, the final keyword means the class can't be subclassed. In other words, no other class can ever extend (inherit from) a final class, and any attempts to do so will give you a compiler error.

    Java access control

    There are two levels of access control:

    * At the top level—public, or package-private (no explicit modifier).
    * At the member level—public, private, protected, or package-private (no explicit modifier).

    Access Levels
    Modifier Class Package Subclass World
    public Y Y Y Y
    protected Y Y Y N
    no modifier Y Y N N
    private Y N N N

    Rules for creating Java source files

    ■ There can be only one public class per source code file.
    ■ If there is a public class in a file, the name of the file must match the name
    of the public class. For example, a class declared as public class Dog { }
    must be in a source code file named Dog.java.
    ■ If the class is part of a package, the package statement must be the first line
    in the source code file, before any import statements that may be present.
    ■ If there are import statements, they must go between the package statement
    (if there is one) and the class declaration. If there isn't a package statement,
    then the import statement(s) must be the first line(s) in the source code file.
    If there are no package or import statements, the class declaration must be
    the first line in the source code file.
    ■ import and package statements apply to all classes within a source code file.
    In other words, there's no way to declare multiple classes in a file and have
    them in different packages, or use different imports.
    ■ A file can have more than one nonpublic class.
    ■ Files with no public classes can have a name that does not match any of the
    classes in the file.

    Java Enums

    Simple enum
    The ; after the last element is optional, when this is the end of enum definition.

    public enum Color {
    WHITE, BLACK, RED, YELLOW, BLUE; //; is optional
    }

    Simple enum embedded inside a class

    public class Outter {
    public enum Color {
    WHITE, BLACK, RED, YELLOW, BLUE
    }
    }
    Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.

    Enum that overrides toString method

    A semicolon after the last element is required to be able to compile it. More details on overriding enum toString method can be found here.

    public enum Color {
    WHITE, BLACK, RED, YELLOW, BLUE; //; is required here.

    @Override public String toString() {
    String prev = super.toString();
    return prev.substring(0, 1) + prev.substring(1).toLowerCase();
    }
    }

    Enum with additional fields and custom constructor

    Enum constructors must be either private or package default, and protected or public access modifier is not allowed. When custom constructor is declared, all elements declaration must match that constructor.

    public enum Color {
    WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);

    private int code;

    private Color(int c) {
    code = c;
    }

    public int getCode() {
    return code;
    }

    Java Beans

    JavaBeans are Java classes that have properties. You could think of properties as private instance variables. If they are private, the they can be accessed from outside of their class through methods in the class.

    JavaBean Naming Rules for properties's members:
    ■ 'is' or 'get' for boolean values, example: boolean isOdd() or boolean getOdd(), boolean isError() or boolean getError();
    ■ get/set for other values

    JavaBean Listener Naming Rules:
    ■ Listener method names which "register" a listener with an event source
    must use the prefix add, followed by the listener type. For example,
    addActionListener().
    ■ Listener method names which unregister a listener must use the prefix remove, followed by the listener type.
    ■ Listener method names must end with the word "Listener".

    Keywords in Java

    The keywords cannot be used as identifiers.

    assert - keyword from java 1.4
    abstract
    boolean
    break
    byte
    case
    catch
    char
    class
    const
    continue
    default
    do
    double
    else
    enum - keyword from java 1.5
    extends
    final
    finally
    float
    for
    goto
    if
    implements
    import
    instanceof
    int
    interface
    long
    native
    new
    package
    private
    protected
    public
    return
    short
    static
    strictfp
    super
    switch
    synchronized
    this
    throw
    throws
    transient
    try
    void
    volatile
    while

    Java Legal & Illegal identifiers

    Legal identifiers:
    int _x;
    int $z;
    int _$$;
    int ___4_a;
    int javatests_dot_blogspot_dot_com;

    Illegal identifiers:
    int :joro;
    int -z;
    int z#;
    int .z;
    int 7z;