Saturday, December 24, 2011

Generics

Must read tutorial:
Sun Java Tutorial

Comparator and Comparable

References:
Link1:
http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

Link2:
http://www.java2s.com/Code/Java/Collections-Data-Structure/WritingYourownComparator.htm

Friday, December 23, 2011

Hashcode & equals

Contract between hashcode and equals as per Java specification -

* Whenever it is invoked on the same object more than once during an execution of a Java application, the hashcode() method must consistently return the same integer, provided no information used in equals() comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.

* If two objects are equal according to the equals(object) method, then calling the hashCode() method on each of the two objects must produce the same integer result.

* It is NOT required that if two objects are unequal according to the equals(Java.lang.Object) method, then calling the hashCode() method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

--------------------------------------------
Sample Buggy code to show bug if same fields are not used to compute equals and hashCode :
--------------------------------------------
package com.examples;

public final class Box {

private final int ssn;
private final int age;

public Box(int ssnval, int ageval) {
ssn = ssnval;
age = ageval;
}

// Magic number 31 (odd and prime) as seed just like java String.
public int hashCode() {
return 31 + ssn;
}

public boolean equals(Object that) {

if (this == that) {
return true;
}

if (! (that instanceof Box) ) {
return false;
}

if ((this.ssn == ((Box)that).ssn) && (this.age == ((Box)that).age)) {
return true;
}

// Bug in code as there is a mismatch of fields between equals and hashcode.
return false;
}

}

package com.examples;

import java.util.*;

public class Test {

public static void main(String[] args) {
Box b1 = new Box(10, 20);
Box b2 = new Box(10, 25);

if (b1.hashCode() == b2.hashCode()) {
System.out.println("Box objects b1 & b2 - hashcodes are same");
} else {
System.out.println("Box objects b1 & b2 - hashcodes are NOT same");
}

if (b1.equals(b2)) {
System.out.println("Box objects b1 & b2 - equals are same");
} else {
System.out.println("Box objects b1 & b2 - equals are NOT same");
}

Map boxmap = new HashMap();
boxmap.put(b1, "TestVal");

String val1 = boxmap.get(b1);
String val2 = boxmap.get(b2);
System.out.println("Val1 = " + val1);
System.out.println("Val2 = " + val2);

}

}

Output demonstrating the bug : val2 is null because of broken contract.
-------------------------------
Box objects b1 & b2 - hashcodes are same
Box objects b1 & b2 - equals are NOT same
Val1 = TestVal
Val2 = null


The above example clearly shows that Java collection uses hashCode first to go to the appropriate bucket. Then uses equals() to see if object matches.

Bug fix: Change hashCode() to use 31 + ssn + age.

*** Note that the above sample uses Immutable Box object demonstration - all final, private and one-shot object construction.


References:
------------
* Implementing HashCode - http://www.javapractices.com/topic/TopicAction.do?Id=28

* http://tech-read.com/2009/02/12/use-of-hashcode-and-equals

Thursday, December 22, 2011

Immutable Objects

* Immutable objects - http://www.javapractices.com/topic/TopicAction.do?Id=29

Advantages and disadvantages of immutable objects :
http://www.codeinstructions.com/2008/07/immutable-classes.html

Terminology:
Value Object : http://c2.com/cgi/wiki?ValueObject

Sunday, December 11, 2011

Struts-1 Basics

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:
* Open source
* Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
* Implements the JSP Model 2 Architecture
* Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.



All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-config.xml is used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions:

** From View to Action :
A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer (Business layer) service or function.

** From Action to View :
After the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser.

=====================
Struts Components
=====================

The Controller :
-----------------------
This receives all incoming requests. Its primary function is the mapping of a request URI to an action class selecting the proper application module. It's provided by the framework.
The struts-config.xml File

This file contains all of the routing and configuration information for the Struts application. This XML file needs to be in the WEB-INF directory of the application.
Action Classes

It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs and business services. Actions process a request and return an ActionForward object that identifies the next component to invoke. They're part of the Controller layer, not the Model layer.

View Resources
-------------------
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource bundles, JavaBeans, and Struts JSP tags.

ActionForms
-------------------
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.

Model Components
--------------------
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:
* JavaBeans
* EJB
* CORBA
* JDO
* any other

=============
SEQUENCE FLOW
==============


The following events happen when the Client browser issues an HTTP request.

* The ActionServlet receives the request.
* The struts-config.xml file contains the details regarding the Actions, ActionForms, ActionMappings and ActionForwards.
* During the startup the ActionServelet reads the struts-config.xml file and creates a database of configuration objects. Later while processing the request the ActionServlet makes decision by refering to this object.

When the ActionServlet receives the request it does the following tasks :-

* Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
* Decides which action class to invoke to process the request.
* Validate the data entered by the user.
* The action class process the request with the help of the model component. The model interacts with the database and process the request.
* After completing the request processing the Action class returns an ActionForward to the controller.
* Based on the ActionForward the controller will invoke the appropriate view.
* The HTTP response is rendered back to the user by the view component.

References:
-----------
Exadel Site
Site-2

Wednesday, December 7, 2011

Conversion and Casting

Tracing technique for casting (primitive data types)
******************************

byte ---> short ---> int ---> long ---> float ---> double
char ----> int ---> long ---> float ---> double

In the above chart, if you can trace path from one element to another element, then that cast is safe (or) implicit cast happens.
For ex: conversion of byte to float is fine as you can trace the path. Reverse (float to byte) is not safe as you cannot trace the path.

****************************************************
Primitive Data Type - Conversion (Implicit Casting)
****************************************************

For primitive data types, this happens in the following cases

1. Assignment operations
int i;
double d;
i=10;
d=i; // Implicit Casting happens here

2. Method call

int i=10;
foo(i); // Implicit Casting happens here

public void foo(long l) {
...
}

3. Arithment promotions
int i =10;
long l = 20;
long result = l/i; // Implicit Casting happens here as part of arithmetic promotions.

****************************************************
Primitive Data Type - Explicit Casting
****************************************************
int i;
long l;
l = (long) i; // Works - even though this is not necessary. Implicit cast happens if we don't specify it.
i = (int) l; // Explicit casting. Narrow down cast always needs Explicit casting. This compiles and works. But result could be unexpected as most significant bits will be lost.


****************************************************
Object References - Conversion (Implicit Casting)
****************************************************
TBD.

****************************************************
Object References - Conversion (Explicit Casting)
****************************************************
TBD.

Reference:
Java Certification Book.

Boxing/Unboxing - Primitive Type wrappers

Java provides Auto Boxing/Un-boxing functionality as we cannot use primitive types to store in Collection framework (deals with Object References).

For each primitive type in Java, we have an equivalent Object wrapper.

boolean - Boolean (1 bit storage for primitive data type)
byte - Byte (1 byte storage for primitive data type)
short - Short ; char - Character (2 bytes storage for short or char - primitive data types)
int - Integer (4 bytes storage for primitive data type)
long - Long (8 bytes storage for primitive data type)
float - Float (4 bytes storage for primitive data type)
double - Double (8 bytes storage for primitive data type)

Boxing / Unboxing functionality in Java does implicit casting during
- assignment
- method invocation.

For examples and more details, refer to the following tutorial
Java Tutorial

Is intern() on String worth the effort?

Link to the analysis

http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html

Wednesday, June 2, 2010

Cheat Sheet

****************************************
1. Multiple Inheritance :
****************************************
Java does not allow multiple inheritance unlike C++. For ex: a child inherits behavior from two parents. So if you consider a child as an class, then it should be able to inherit from both Mom class and Dad class. So it makes sense to have this multiple inheritance. However Java does not support this. Reason as cited by many authors is, design complexity outweighs its advantages. So Java does not have it.
* However Java supports implementaion of multiple interfaces.

****************************************
2. Operator Overloading :
****************************************
There is no Operator overloading in Java. Java does overloading of + sign to concatenate strings. That is the only overloaded operator in Java. Reason for not providing this option in Java is, problems associated with operator overloading outweigh its advantages. Code becomes confusing and difficult to sustain. So they avoided it.

****************************************
3. Order of allocation in creating a new object :
****************************************
(a) Constructor of the super class is invoked. This takes first precedence.
(b) Initialization of class and object attributes. These are not attributes initialized in the constructor. But instance variables of scope class and object.
(c) Code in the constructor executes.

****************************************
4. Best way to do error handling :
****************************************
Throw Exceptions to the logical point. Caller should be able to fix the problem and re-invoke it.
Fixing the problem could be through
(a) Retry an operation
(b) Collect different data from users.
(c) Report problem back to users.

****************************************
5. Attribute scopes :
****************************************
(a) Local attributes : Declared and initialized inside methods of a class. If local attributes have same name as object attributes, you can specifically invoke object attributes by using "this" operator. "this" refers to the object here.
(b) Object attributes: Not shared between different object instances of a class. These are non-static data members of a class definition.
(c) Class attributes: Shared between all object instances created from that class. These are static data members of a class definition.

****************************************
6. Copying objects :
****************************************
Objects have references to sub objects. This leads to two types of copying - Shallow Versus Deep Copy. You need to provide an implementation for copy method to do a deep copy by traversing through all sub-objects following references. Else you will end up in shallow copy.

****************************************
7. Comparing objects :
****************************************
Just like we have Shallow Versus Deep copy, we also have Shallow versus Deep compare. So you need to provide an implementation for compare method to do a deep compare by traversing through all sub-objects following references. Else you will end up in shallow compare.

****************************************
8. Dangling pointers:
****************************************
TBD

****************************************
9. Garbage Collection:
****************************************
TBD.
Does Java support GC of circular references? - TBD

****************************************
10. MT-Safe
****************************************
1. How does locks work on synchronized methods?
Refer to this tutorial

****************************************
11. Call by value or Call by reference?
****************************************
Refer to this detailed article
CodeGuru Article

****************************************
12. Nested Classes
****************************************
Static inner nested class:
JavaWorld Article

Inner Classes
JavaWorld Article

****************************************
13. Collection
****************************************
Two concepts:
a) Collection :
It is a group of individual elements, often with some rule applied to them. Contains

(i) List -
* A List holds the elements in a particular sequence.
* Allows duplicate values.

(ii) Set -
* No sequence. Just a bag of elements.
* Does not allow any duplicate elements.

b) Map :
(i) It is a group of key-value object pairs. A Map can return a Set of its keys, a Collection of its values, or a Set of its pairs.
(ii) Like Arrays, it is possible to have multiple dimensions without extra implementation. This can be obtained by making value of a key another map.

Commonly used data structures :
-----------------------------------------------
Interface : Concrete Implementation
-----------------------------------------------
Set : HashSet
List : ArrayList
Queue : LinkedList
Map : HashMap / HashTable
SortedSet : Dictionary
----------------------------------------------

Unordered Collection Interface:
1. Collection
2. Set
3. List
4. Queue
5. Map

Ordered Collection Interfaces
1. SortedSet
2. SortedMap

Summary of interfaces


******************** END of CHEAT SHEET ********************