Sunday, July 13, 2008

SCJP Exam - Objective 1.3 Part II

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.

Arrays are objects in Java that store multiple variables of the same type. Arrays can hold either primitives or object references, but the array itself will always be an object on the heap, even if the array is declared to hold primitive elements. In other words, there is no such thing as a primitive array, but you can make an array of primitives.

There are three things, what you should know about array:
  1. declaring array
  2. constructing array
  3. initializing array

Declaring arrays
Arrays are declared by stating the type of element the array will hold, which can be an object or a primitive, followed by square brackets to the left or right of the identifier.

Declaring array of primitives
Declaration of an array of primitives looks like this:
<primitive type>[] <identifier>;

for example:
int[] integer_array;

There is another way to declare arrays (like in language C):
<primitive type> <identifier>[];

for example:
int anotherArray[];
Declaring array of objects
Declaration of array of objects:
<classname>[] <identifier>;

for example:
String[] stringArray;
Array of object can be declared as in language C too.

Declaring multidimensional arrays
Java let you to declare multidimensional arrays. Multidimensional arrays are arrays of arrays.
A two dimensional array declaration:
String[][] twoDimensionalArray;

The
String[][] threeDimensionalArray[];

declaration is interesting, but legal.

Constructing arrays
Constructing an array means creating the array object on the heap. To create an array object, Java must know how much space to allocate on the heap, so user must specify the size of the array at creation time. The size of the array is the number of elements the array will hold.

Examples
int[] intArray; //Declare an one-dimensional array
intArray = new int[3]; //Construct an int array to hold 3 int value
long longArray = new long[1]; //Declare and construct a long array with one element


Constructing multidimensional array
Remember, multidimensional arrays are simply arrays of arrays. It means, elements of multidimensional arrays are arrays.
The
int[][] array = new int[2][];

means we declare and construct a two-dimensional integer array and the size of the first dimension will be 2. When we initialize the array then we can put int array as elements with different size into the array.
The
int otherArray = new int[3][2];

means we declare and construct a two-dimensional integer array and the size of the first dimension will be 3 and declare and construct three one-dimension array with length 2 and put them into the array.

Initializing arrays
Initializing an array means putting things (primitives, object references) into it:
int[] a = new int[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
int b[] = new int[2];
b[0] = 8;
b[1] = 9;
int[][] c;
c = new int[2][];
c[0] = a;
c[1] =b;
String[] s = new String[3];
s[0] = "hello";
s[1] = null; //null can be use as string element
s[2] = new String("World");

Notice, array indexes begin with 0 and go to size-1. If we try refer to an index that not exist (for example a negative number, or a number greater then size-1) then ArrayIndexOutOfBoundsException trowed.

Declaring, constructing and initializing arrays
It's possible to declare, construct and initialize array in the same time:
int[] a = { 5, 6, 7 };
String lenovo = new String("Lenovo");
String[] computerProducers = { "Dell", lenovo, "HP", "Apple" };

Anonymous array creation
Anonymous array creation can be used to construct and initialize an array, and then assign the array to a previously declared array reference variable:
String[] operatingSystems;
operatingSystems = new String[] { "Windows XP", "Windows Vista", "OpenSuSE 10.3" };

Multidimensional array creation
Multidimensional array creation looks like this:
int[][] array = { { 1, 2, 3 }, { 10, 11 }, { 0 } };

Declare, initialize and uses arrays, enums, objects as static, instance and local variables
Example code:

You can download source code here.

Thursday, July 10, 2008

Spring Framework - Introduction

Spring is an open-source framework, created by Rod Johnson. It was created to address the complexity of enterprise application development. Spring makes it possible to use JavaBeans to achieve things that were previously only possible with EJBs. However, Spring’s usefulness isn’t limited to server-side development. Any Java application can benefit from Spring in terms of simplicity, testability, and loose coupling.

Web: http://www.springframework.org/

Lightweight — Spring is lightweight in terms of both size and overhead. The entire Spring framework can be distributed in a single JAR file that weighs in at just over 1 MB. And the processing overhead required by Spring is negligible. What’s more, Spring is non intrusive: objects in a Spring-enabled application typically have no dependencies on Spring specific classes.

Inversion of control — Spring promotes loose coupling through a technique known as inversion of control (IoC). When IoC is applied, objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. You can think of IoC as JNDI in reverse—instead of an object looking up dependencies from a container, the container gives the dependencies to the object at instantiation without waiting to be asked.

Aspect-oriented — Spring comes with rich support for aspect-oriented programming
that enables cohesive development by separating application business logic from system services (such as auditing and transaction management). Application objects do what they’re supposed to do—perform business logic—and nothing more. They are not responsible for (or even aware of) other system concerns, such as logging or transactional support.

Container — Spring is a container in the sense that it contains and manages the life cycle and configuration of application objects. You can configure how your each of your beans should be created—either create one single instance of your bean or produce a new instance every time one is needed based on a configurable prototype—and how they should be associated with each other. Spring should not, however, be confused with traditionally heavyweight EJB containers, which are often large and cumbersome to work with.

Framework — Spring makes it possible to configure and compose complex applications from simpler components. In Spring, application objects are composed declaratively, typically in an XML file. Spring also provides much infrastructure functionality (transaction management, persistence framework integration, etc.), leaving the development of application logic to developer.

Starting with Spring Framework
Downloading required files
You can download the latest release of Spring framework from this link. Select the spring-framework-2.x.z-with-dependencies.zip file, that contains the base files and the files to use Spring modules.

Unpacking file
Unpack the downloaded zip file to a directory. The directory structure, that is created looks like this:
The [lib] is the most important directory, the JAR files to Spring extensions are here.

Creating the first Spring application
Our sample application will have a service interface and implementation, what writes the Hello World to the console.

Required JAR files
To build and run our first application using Spring framework, we must add the following JAR files to the classpath:
  • spring.jar
  • spring-core.jar
  • spring-context.jar
  • commons-logging.jar
  • log4j-1.2.xy.jar
You can see, Spring is really lightweight.

Creating the Service interface
I don't discuss this step, this is a simple interface declaration.

Source code:

Implementing the interface
This is an easy step too, a simple interface implementation, I hope everyone realizes it.

Source code:

Creating configuration XML file
This is the first step, where we see something new: the XML configuration file. These files are the "heart of Spring". Here are the bean definitions, configuration data, I discuss it later in detail.

In brief, we create 3 instance of GreetingServiceImp with identification
  • greetingService
  • inheritedGreetingService
  • wrongGreetingService
GreetingServiceImp has two user-defined property:
  • greetingMessage
  • name
The
<bean id="greetingService" class="spring.example.helloworld.GreetingServiceImp">
<property name="greetingMessage">
<value>Hello</value>
</property>
<property name="name">
<value>World</value>
</property>
</bean>
bean definition means:
  1. create a spring.example.helloworld.GreetingServiceImp instance,
  2. set the property greetingMessage to "Hello",
  3. set the property name to "World",
  4. assign the greetingService identification to the instance.

XML file:

Running the code
The running code gets the three GreetingServiceImp instance from the ApplicationContext and calls the sayHello() methods.
The
ApplicationContext context = new ClassPathXmlApplicationContext("greeting.xml");

line create an ApplicationContext instance. Through this context we can access the beans defined in greeting.xml file, like this:
GreetingService greeting = (GreetingService) context.getBean("greetingService");

Source code:

Downloads
You can download this sample application as NetBeans project with dependencies here.

Tuesday, July 8, 2008

Applying Model Viewing Controller to Java Web Applications Using JSP and Servlet

Model viewing controller is an architectural pattern. We can use to separate the user interface and the business logic. By decoupling models and views, MVC helps to reduce the complexity in architectural design, and to increase flexibility and reuse.


It isn't goal of this post to explain the using JSP and Servlet technologies. Maybe in another post I will do it.


Participants of the Model Viewing Controller Design Pattern
(based on Wikipedia)

model - the domain-specific representation of the information on which the application operates. Domain logic adds meaning to raw data (e.g., calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be underneath or encapsulated by the Model.
viewing - renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes.
controller - processes and responds to events, typically user actions, and may invoke changes on the model.

A simple diagram depicting the relationship
between the Model, View, and Controller.


Model Viewing Controller in action
  1. The user interacts with the user interface.
  2. A controller handles the input event from the user interface, often via a registered handler or callback.
  3. The controller notifies the model of the user action, possibly resulting in a change in the model's state.
  4. A view uses the model (indirectly) to generate an appropriate user interface. The view gets its own data from the model. The model has no direct knowledge of the view.
  5. The user interface waits for further user interactions, which begins the cycle anew.



Model Viewing Controller in action


Participants of the Model Viewing Controller Design Pattern - Java Web Application Using JSP and Servlet

model
- a web application usually operates on database. There are several ways to access database from web application (JDBC, Hibernate, Toplink...).
viewing - Java Server Pages (JSP) can be used as user interface. With JSP technologies we can generate contents to web browsers, mobile phones, XML files.
controller - Servlets was developed to control the web application and access to the database, what the application use.

Model Viewing Controller in action - Java Web Application Using JSP and Servlet

In the first step, the user visits a web portal with his web browser:


Example web application

The viewed content is generated by a viewer, a JSP file:

By clicking Greeting! button, the given name will be sent to the controller Servlet. In this time the form's content is sent to the specified controller (action property, in this case greeting.controller). The property method specify the type of request (GET or POST).

The controller, in this case the GreetingServlet get the http request.
The servlets have two entry point, depends on it get a http GET or http POST query:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
So depend on the type of request, the suitable method is invocated, the specified codes begin to run.

In my example the servlet looks like this:

The servlet processes the data and the processing is forwarded to the result.jsp, where greetings message will be showed:

Downloads
You can download example code here as NetBeans project.

Friday, July 4, 2008

SCJP Exam - Objective 1.3 Part I

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.

Legal identifiers
Technically, legal identifiers must be composed of only Unicode characters, numbers, currency symbols, and connecting characters (like underscores).
  • Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ).
  • Identifiers cannot start with a number!
  • After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers.
  • There is no limit to the number of characters an identifier can contain.
  • Java keywords can't be used as identifier.
  • Identifiers in Java are case-sensitive.

Java keywords

abstractassertbooleanbreak
bytecasecatchchar
classconstcontinuedefault
dodoubleelseenum
extendsfinalfinallyfloat
forgotoifimplements
importinstanceofintinterface
longnativenewpackage
privateprotectedpublicreturn
shortstaticstrictfpsuper
switchsynchronizedthisthrow
throwstransienttryvoid
volatilewhile


Static variables
  • static variables belong to the class, not the instance
  • static variables can be public, protected, default and private
  • static variables can accessed through class reference
  • access static variables through instance variables is legal, but not a good idea
  • static variables get their default value at declaration
  • static variables declared when the class loader load their class
  • static variables live as long as their class lives
  • static variables can declared and initialized at the same time, except when the initialization can throw exception, in this case use static initialization block:
//Required imports here
...
class ThisClassUseStream {
//Compilation fails, because FileInputStream constructor can throw exception.
static InputStream stream = new FileInputStream("filename");

//Works well, otherStream declared and initialized as null.
static InputStream otherStream;

//static initialization block
static {
try {
otherStream = new FileInputStream("filename");
} catch( Exception ex } { ... }
}
}
  • static initialization block execute top-down
  • static variables are not inherited
  • static variables cannot be serialized

Instance variables
  • instance variables belong to an object instance
  • instance variables can be accessed only through an instance
  • instance variables can be accessed from somewhere in their instance
  • instance variables can be public, protected, default and private
  • instance variable can be inherited
  • private variables are not inherited
  • variables with default visibility are not inherited
  • instance variables are created when the constructor is called
  • instance variable get their default values at declaration

Local variables
  • local variables are created inside a method body
  • local variables live as long as their method is running
  • local variables can be accessed only the method where they was declared
  • local variables don't have default values
  • local variables can be marked only as final

Variables - default values
  • boolean variables: false
  • byte variables: 0
  • char variables: '\u0000'
  • double variables: 0.0D
  • float variables: 0.0F
  • int variables: 0
  • long variables: 0L
  • object references: null
  • short variables: 0
Do not forget, only static and instance variables have default values!

Declare, initialize, use primitives as static, instance and local variable
The Java programming language is strongly-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:
int a = 5;
Primitive types
There are 8 primitive type in java:
  • boolean data type has only two possible values: true and false.
  • byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
  • char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
  • double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values isn't important.
  • float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values isn't important.
  • int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
  • long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
  • short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).
Default values of data types are showed above.

Primitive and string literals

Integer literals

There are three ways to represent integer numbers in the Java language:
  • decimal (base 10)
  • octal (base 8)
  • hexadecimal (base 16)

Decimal literals
Decimal representation is the most common in Java, for example:
int a = 1;
long l = 5L;
byte b = 0;
short s = 8;

Octal literals
  • octal literals use only the digits 0 to 7
  • octal literals always begin with 0
  • octal literals can up to 21 digits in an octal number, not including the leading zero
So don't forget,
o77 != 77

because 077 is the octal representation of number 63.
  • some octal literals:
int a = 07 //equals decimal 7
int b = 08 //compilation fails, 8 digit not allowed
int c= 01234 equals decimal 668


Hexadecimal literals
  • hexadecimal numbers are constructed using 16 distinct symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A (or a), B (or b), C (or c), D (or d), E (or e) , F (or f)
  • hexadecimal literals always begin with 0x or 0X
  • hexadecimal numbers can be up to 16, not including the prefix Ox
Floating-point literals
  • floating point literals include the decimal point (.)
  • the left side of decimal point is the integer part
  • the right side of decimal point is the fraction part
  • one of the integer or the fraction part must be declared
  • legal declaration and initialization:
double d1 = .1;
double d2 = 1.;
double d3 = 1.d;
double d4 = .3D;
double _____________ = -.66d;
float f1 = 9.66f;

  • not legal declaration and initialization:
double d3 = .;
float f1 = 0.0;
Boolean literals
  • there are two boolean literals: true and false
Character literals
  • character literals can declared between two single quotes
  • character literals can declared as number
  • legal character literals:
char c1 = 'a';
char c2 = '\u00ff';
char c3 = 32;
char c4 = 04;
char c5 = 0xf;
String literals
  • string literals are declared between two double quote
  • string literal declaration:
String s = "Hello World";
Declaration Example

You can download source code here.

Casting primitives
Casts can be implicit or explicit. An implicit cast means you don't have to write code for the cast; the conversion happens automatically. Typically, an implicit cast happens when you're doing a widening conversion.

Implicit cast
byte b = 5;
int i = b;

Int type is bigger the byte, implicit cast work.

Explicit cast
We need use explicit cast, if we want to assign a bigger value to a smaller type. It can cause loss of procession so explicit cast is required.
Explicit cast look like this:
int a = (int) 5.5; //5.5 is a double, it must be cast to int
byte b = (byte) 128; //128 is too big to store in a byte
byte c = 100;

Tuesday, July 1, 2008

SCJP Exam - Objective 1.2

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.

Interface declaration
This is discussed in Objective 1.1 - Interface declaration.

Do not forget, what is in the Objective 1.1 written about interface declarations.

Extend an interface
  • an interface can extend one or more other interfaces

  • an interface cannot extend anything but another interface


Abstract class declaration
abstract class <ClassName> {
//...
}

You can read more about abstract classes in Objective 1.1 - Non-access modifier: abstract.

Extend an abstract class
  • a class can extend only one class (no multiple inheritance)
  • abstract class can extend concrete and abstract classes


Example for interface declaration, interface implementation, abstract class declaration, abstract class extension:

You can download source code here.