Sunday, May 23, 2010

PHP essentials for Java programmers

I recently had to do a project in PHP and being from Java background one notices enumerable similarities. Obviously the whole knowledge about object-oriented programming and the procedural constructs like assignments, statements, conditions, loop etc are totally transferable. However the key difference I noticed was in the function calls. In Java all the arguments are passed by value, even for the objects, ie we pass the copy of the address for the object. But in PHP we are allowed to pass arguments by value or reference. Thus we have a simple function

function writeName($name) { echo $name; }

it passes the $name argument as value. However, by just prefixing $name with an ampersand we pass the argument by reference to give

function writeName(&$name) { echo $name; }

The other clever thing about PHP function is that we can return a value by reference too. Take the example from Joomla! library:


function &getLanguage()
{
static $instance;

if (!is_object($instance))
{
//get the debug configuration setting
$conf =& JFactory::getConfig();
$debug = $conf->getValue('config.debug_lang');

$instance = JFactory::_createLanguage();
$instance->setDebug($debug);
}

return $instance;
}

Preceding the getLanguage() function by an ampersand indicates that the function will return a value by reference, thus the return is a pointer to $instance.

The another line which will puzzle Java programmers above is

$conf =& JFactory::getConfig();

=& the syntax simply means that $conf is being assigned reference to the object created by getConfig() method of JFactory class. :: notation indicates that we are invoking a class method rather than an instance method. The normal Java dot notation of object.method() for invoking an instance method is changed in PHP to object->method()

Armed with the knowledge in this article a Java programmer is ready to do a PHP project. The only other thing to bear in mind is that the class constructor is defined by function __construct(). Obviously one will have to come to grips with various PHP functions but this should be no different from understanding a new Java API.

Friday, April 23, 2010

Selectors in Cascading Style Sheets

The indispensable tool  in every web developers portfolio is Cascading Style Sheets (CSS). Once HTML has been used to organize the contents, the presentational brilliance stems from using CSS rules. Syntactically the rules have a selector followed by a declaration containing various properties separated by semicolons:

p {color:blue; font-weight:normal;}

This simple tag selector rule colours all the contents of
tags in the HTML document. Also noted that the property-value combination is defined by separating the property from its value with a colon.  Instead of p we could have used any of the html elements like h1, h2 etc. To apply the rule to a group of elements we simply use a selector with comma separated the elements. For example, if we want to override the h3, h4, h5 and h6 header elements default definition of the browser, we can just use group selector:

h3, h4, h5, h6 {color:black; font-size:1.2em;)

The commonest way of formatting content is to use the class selector in conjunction with <div> block element or <span> inline element.

.myClass {color:black; font-size:1.2em;) class selector has a period prefix. Currently it will apply to any tag which has attribute definition of class="myClass". For example, if we have the following in our document:

<p class="myClass">...</p>
<div class="myClass">...</div>

then the .myClass selector will apply the declaration formatting to both these elements. To just restrict the formatting to
element, we change the selector to p.myClass in our rule.

Along with class, id is another attribute which can be placed on most elements. Indeed, javascript uses id to get the elements. So if we have <p id="myID"> then the hash prefixed selector for this element becomes:

#myID {color:black; font-size:1.2em;)

We also have pseudo-classes and pseudo-elements available as selectors. The anchor pseudo-classes are used to invariably define link interaction with a:link, a:visited, a:hover and a:active selectors. We know that these stages happen with links. Similarly, the first line of a paragraph or a first letter of the paragraph doesn't have a tag but it is easily identifiable pseudo-element so we can have a selectors like:


p:first-letter {color: blue;font-size:1.5em;}


or

p:first-line {color: blue;font-size:1.5em;}

Similarly there are pseudo-elements after and before for auto-generated content. To prefix a paragraph with a class="intro" with 'Thought of the day!' auto-generated content, we have the selector syntax:

p.intro:before {content: "Thought of the day!" }

or to give the text after the paragraph:

p.intro:after {content: "Thought of the day!" }

To style tags within tags we have descendant selector. For example, to highlight emphasis within a paragraph we may use the selector:

h1 strong { color: red; }

Here sub-element <strong> within element <h1> is coloured red. Similarly if we wanted to select the ordered lists which are direct children of body element the syntax is body > ol for the rule. Note the angle bracket is used for the child selector. Or to get to an adjacent sibling we use the plus ('+') sign instead of the angle bracket.

We can also select on the attributes. These selectors allow us to select element which have a certain property. For example to select all the images with title attribute we will have a selector img[title]. Or to just select text boxes in a form we can have the attribute selector

input[type="text"]

There are some further refinements to these selector but the knowledge is acquired by experimentation. The aspects covered are more than adequate.

For a good source for understanding the selectors visit here.

CSS: The Missing Manual is a very useful resource which you should have in your collection.




 

Wednesday, April 14, 2010

Delight of w3schools

Like countless other people I have used the tutorials at w3schools to become familiar with various technologies at different stages in my life. It is impossible to be not familiar with this site for anyone who has taken delight in learning new things. I recall learning about ASP, XPath etc on this site a number of years ago. Indeed a career in IT is impossible without constantly updating ones skill base so a comprehensive training resource is a real boon. The site invariably appears in the top searches whenever 'Ajax tutorial' or 'jquery tutorial' type terms are used in google so cannot escape the radar of any technology aficionado. For last couple of years I had been hearing good things about jquey so decided to take the plunge and become familiar with the framework yesterday. Needless to say that w3schools gave me a couple of hours of real pleasure. There tutorial seem basic but they get to the heart of the matter. Their examples were lucid and their jquery engine for practising is great. So here is a public thanks for being so useful. W3schools, you rock!

Wednesday, March 31, 2010

The brave new world

The pressure on IT has always been there to deliver. I recall the 80s when the business-IT alignment was on everybody's lips, the 90s when the IT-facilitated business process re-engineering and kaizan were talk of the town and the new economic order was proclaimed by the web-based companies at the turn of the century. IT was always deemed indispensable in these initiatives but adjudged to be slow to meet the business needs. The bursting of the dotcom bubble and the y2k experience tarnished the IT image but did not abet the pressure on IT to facilitate inter-organisational processes in a globalised world. IT's role was still at the heart of 'making it happen'. One assumed that the ERP systems had taken care of all the transactional needs at the operational level and the datawarehouses and business intelligence tools had enamoured the business executives by adding value to strategy formulation. Now comes the frightening reminder that all is not well in the wake of global financial meltdown.

"Capital expenditure priorities are shifted into IT from other high-payback projects" just to perform necessary ERP changes, claims one executive. Whilst another bemoans: "Change to ERP paralyzes the entire organization in moving forward in other areas that can bring more value."

An Accenture partner sees rising tide of operational flexibility on daily basis and proclaims "strategy, as we knew it, is dead." A paradigm shift in IT's execution is expected and demanded in this new world order. Yet the top priority for 2009 was "modernizing key legacy applications" and the SOA, the pre-requisite for flexibility, seemed fatally wounded.

It is a challenge to all the IT professionals to acquire a mindset attuned with business imperatives and successfully deploy disruptive technologies to make a quantum change. The decade ahead of us is full of potential and we must not fail.

Tuesday, March 30, 2010

SOAP with Attachment API for Java (SAAJ) example

SAAJ is an indispensable tool for manipulating SOAP messages, especially if they have got attachments. We have illustrated all the steps in creating a SwA (SOAP Messages with Attachments) in the short self-explanatory example which can be adapted for all purposes.

package saajexample;

import java.awt.Image;
import java.awt.Toolkit;
import javax.xml.soap.*;

public class Main {

public static void main(String[] args) throws Exception {
// Factory needed to create SOAP message
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
// illustrate the story so far by dumping out the message
message.writeTo(System.out);
// detach the header from the SOAP Envelope
message.getSOAPHeader().detachNode();
System.out.println("");
message.writeTo(System.out);
// manipulate the body of the SOAP message
SOAPBody body = message.getSOAPBody();
SOAPElement getStockPrice = body.addChildElement(
"getStockPrice",
"rt",
"http://www.rajeev.com/jws/StockQuote");
System.out.println("");
message.writeTo(System.out);
getStockPrice.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);
System.out.println("");
message.writeTo(System.out);
SOAPElement code = getStockPrice.addChildElement("stockCode");
System.out.println("");
message.writeTo(System.out);
code.addTextNode("IBM");
System.out.println("");
message.writeTo(System.out);
// attach an image
Image image = Toolkit.getDefaultToolkit().createImage("raj.jpg");
AttachmentPart jpegAttach = message.createAttachmentPart();
// use setDataHandler method below if connecting to FileDataSource object for pdf file
jpegAttach.setContent(image, "image/jpeg");
// add the mime type for the image
jpegAttach.addMimeHeader("Content-Transfer-Encoding", "binary");
jpegAttach.setContentId("xxx");
message.addAttachmentPart(jpegAttach);
System.out.println("");
// message.writeTo(System.out); // cannot stream image
// check attachment created successfully
System.out.printf("Number of attachments: %d%n", message.countAttachments());
// remove the attachment and verify
message.removeAllAttachments();
System.out.printf("Number of attachments: %d%n", message.countAttachments());

}
}

Monday, March 29, 2010

JAXB tutorial

XML is the lingua franca of the web services world. Unsurprisingly, the ability to process XML documents simply is an essential requirement. To my mind DOM and SAX parsers are the equivalent of assembler programming compared to the high-level programming provided by the Java Architecture for XML Binding, JAXB. It is an essential tool in every Java developer's portfolio. But many tutorials on the web hark back to JAXB1.0 so here is something to get you started.

The JAXB tutorial provided by Rose India is rather dated now. The IBM resource was a fairly good introduction to Java-XML mapping once upon a time but the Sun/Oracle JAXB tutorial is simply amazing.

Rarely a tutorial is written which is as comprehensive as the one provided here. All the aspects of mapping XML Schema Language types to Java, marshalling Java-based tree content to XML, unmarshalling from XML-to-Java, ObjectFactory class, XML annotations, the JAXB schema compiler (xjc) et al have been covered very lucidly.

If it still doesn't satisfy your curiosity then the book JAXB 2.0 is all you need for all the JAXB requirements but unfortunately it is in German.

Here is a sample code to marshal and unmarshal a simple letter written by me to Helen of Troy.

package raj;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Letter {

/**
* The sender of the letter.
*/
private String sender;
/**
* The receiver.
*/
private String receiver;
/**
* A unique number for the message number sent .
*/
private int messageNo;
/**
* The missive despatched.
*/
private String message;

public Letter() {
}

public String getSender() {
return sender;
}

public void setSender(String sender) {
this.sender = sender;
}

public String getReceiver() {
return receiver;
}

public void setReceiver(String receiver) {
this.receiver = receiver;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public int getMessageNo() {
return messageNo;
}

@XmlAttribute
public void setMessageNo(int messageNo) {
this.messageNo = messageNo;
}

public String toString() {
return String.format("Letter %s from %s to %s, saying '%s'", messageNo, sender, receiver, message);
}

public static void main(String[] arg) {
Letter text = new Letter();
text.setSender("Rajeev Trikha");
text.setMessageNo(2010);
text.setReceiver("Helen of Troy");
text.setMessage("Welcome to my world of JAXB in 2010!");
// Create a JAXB context and a marshaller
try {
// here just using a class as an argument but normally is a package
JAXBContext context = JAXBContext.newInstance(Letter.class);
Marshaller marshaller = context.createMarshaller();
// Set the output in formatted manner
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Make the actual serialization

marshaller.marshal(text, new File("raj.xml"));
Unmarshaller unmarshaller = context.createUnmarshaller();
// Get the object
Letter msg = (Letter) unmarshaller.unmarshal(new File("raj.xml"));
System.out.println(msg);
} catch (Exception e) {
System.out.println("exc");
}

}
}

The marshalled file raj.xml shows the created XML message which is well indented.

The unmarshalling prints out to the console:
Letter 2010 from Rajeev Trikha to Helen of Troy, saying 'Welcome to my world of JAXB in 2010!'

If you are using Netbeans then check out for understanding how xjc is tied up within the product.

Saturday, March 20, 2010

CORBA or web services

CORBA has the key advantage of being truly object-oriented component architecture and comes with a host of standard services like naming, transactions, printing, events etc which support complex applications in a heterogeneous environment in a platform and language independent manner. For example, there is no equivalent of CORBA Security service in web service environment and only now the suppliers have started addressing these aspects. So the disadvantage of web services over CORBA is that it is reinventing-the-wheel and cannot handle the required amount of complexity in its current state. However the complexity of CORBA, the issues with its specification and the slowness of new development have opened way for web services which are more suited to web-environment with their loose coupling, XML and HTTP usage. The SOAP messages of web services are simple to use and implement. Unsurprisingly, this simplicity has given momentum to web services over CORBA.

Java Web Services: Up and Running is one of the most up-to-date and practical books on web services.

W3C standards for web services

The key W3C standards for web services are SOAP (previously Simple Object Access Protocol), eXtensible Markup Language (XML), Web Services Description Language (WSDL) and, peripherally, Universal Description, Discovery and Integration (UDDI).

SOAP is protocol which facilitates message-based communication between heterogeneous systems using XML over HTTP (usually) in a defined form. The SOAP message envelop is well-formed, its tags are qualified by a namespace, avoids firewall issues as HTTP port is always open and is part of the body of HTTP request or response.

XML has become the de facto standard for exchanging data between systems as it segregates the meaning of data from its presentation in a plain Unicode text file. SOAP, WSDL and UDDI entries use XML. XML Schema Definition (XSD) is W3C standard for constraining documents vocabularies. The XML files are inherently readable, compressible, portable and support internationalisation, which are pre-requisites in a complex heterogeneous environment. To testify to its popularity, the vocabularies with defined elements and attributes exist for various business domains and the language is extensible. It has become the lingua franca of inter-system communication. SOAP protocol and WSDL descriptions use it. XML messages can be sent over HTTP channels, XML parsers exist in abundance and Data Type Definitions (DTD) or XML Schemas of various vocabularies means that irrespective of platform and implementation language a received XML document can be checked for conformance and meaning and facilitates communication.

WSDL provides platform-independent definition of interfaces of a web service. A WSDL definition describes the location, protocol, service operations, parameters etc in an XML file thus facilitating the segregation of description from the actual implementation. The definition enables one to understand the service and its operations and invoke them.

The UDDI specification is managed by OASIS but it is so central to web services use that it will be churlish to avoid it. UDDI enables web services to be registered and discovered in standard way. The creators of web services register their services in the registry and the potential customers/users discover them there and use them. The white pages, yellow pages and green pages of UDDI entries are well understood and utilised by all who are interested in services-oriented architecture.

Java training course to pass SCJP 6 in Kingston-Upon-Thames

If you live in the vicinity of Kingston-Upon-Thames or are based in London then here is an excellent opportunity to learn Java for £300. Obviously the intention of the course is to give a thorough grounding in Java but the course is structured around the objectives of SCJP 6. You do not need any prior exposure to programming or Java to do this course.

We will use Netbeans IDE and focus on the objective of SCJP 6. The idea is to make students comfortable with all the relevant classes in JDK 6 and have good foundational knowledge of object orientated concepts like inheritance polymorphism, and encapsulation.
The SCJP focuses on modifiers, wrapper classes, autoboxing, flow control, loops, exceptions, APIs, serialization, threads, packaging (JARs), collections, generics, garbage collection, assertions, regular expressions, var-args, covariant returns, static imports, enum, inner classes etc and we will cover all these aspects of Java language over the five days. The IDE hides complexity so we will do some command line compilation and running of programs to give a clear feel for how packages work and the various flags in java and javac

What is most important is that we will provide the support till you actually pass the SCJP exam. Note that the Prometric centre examination fees are not covered in the course cost.

For more information either phone me at 0208 541 0225 or email rajeev108@gmail.com

SCJP Sun Certified Programmer for Java 6 Exam 310-065 is the recommended book if you really want to come to grip with the language and pass the SCJP.

Monday, March 15, 2010

Return of some useful plugins in Netbeans6.9

The introduction of Netbeans6.8 was a mixed blessing. Its support for JSF2.0 and ease of development at various-fronts is indeed praiseworthy but the downside was that we lost many useful plugins including visual web tool for JSF development, UML editor, XML schema editor etc. The howls of anguish were widespread. Sun justified it on the basis of instability of some of the tools and the strategic need to marshal resources on winning fronts. Well, Netbeans6.9 early release have some of these back. It indeed is a good news for champions of these tools but it leaves the question answered on the future direction of these tools in the hands of Oracle. The departure of Sun's CEO Jonathan Schwartz, the chief open source officer Simon Phipps and Java technology evangelist Sang Shin (whose javapassion.com was a useful tool for learning various Java technologies) is indicative of the winds of change. Are these back because of the transitional uncertainties? Whatever the reason, enjoy while they are available.

Many know how to add a new plugin in Netbeans using Tools/Plugins/Available Plugins but fewer are certain of Tools/Plugins/Downloaded/Add Plugins which allows the .nbm (the Netbeans distribution files or Netbeans Modules files) to be incorporated in our 'User Installed Plugins) section. The latter option is the one you need to use if you are downloading a zip file from the Sun's site with the appropriate plugin and want to include it in your environment.

I recall an interview of Leo Apotheker (SAPS's ex-CEO) at Charlie Rose last year where he surmised that SAP may even get in the business of producing hardware devices. The rationale was that the software could easily integrate into remotely monitoring utilities meters and other devices and as BI Accelerator shows that the marriage is inevitable in many cases. Whilst there is feverish speculation on the direction of Java, MySql, OpenOffice etc under the aegis of Oracle, it may well be that it is the hardware/software marriage which underpins the acquisition. But it is hard to remain sanguine about these technologies future under a profit-driven acquisitor like Oracle. The Netbeans tools mentioned above may have gained temporary life while Oracle rationalises their product portfolio. So let us temporarily enjoy their availability whilst there are transitional uncertainties.

Creating and consuming a web service using Netbeans

Here are the steps for creating a simple service which allows two numbers to be multiplied:
  • create a new web application project called MultiplyApp (File/New project/Java Web/Web Application)
  • Click on the MultiplyApp node in the project and add a new web service called MultiplyWS (new/Web Service and type MultiplyWS as the Web Service Name and raj as the Package)
  • Expand the new created Web Services folder and look at the source of MultiplyWS. The default skeleton code should be showing error on MultiplyWS class as it has no operation as yet.
  • Right click within the class definition and define the multiply operation with long return type and two int type parameters i and j (insert Code/Add Web Service Operation)

  • Change the MultiplyWS. java code from return 0; to return i * j;
  • Right click on the MultiplyApp node and select Deploy to deploy the web service.
  • Right click on MultiplyWS in Web Service folder and select Test Web Service to see the service behaviour.
  • Right click on MultiplyApp and select Properties and then choose Run category and change the relative path to /MultiplyWSService?Tester
At this stage our service is ready but we need service consumers which can be any Java application, a servlet or a JSP. We cover the steps for the Java application in some detail but the process for creating a JSP or servlet consumer follows the same pattern.

  • Create a new Java application project called MultiplyClient (File/New Project/Java/Java Application). Leave the Create Main Class box checked while creating.
  • Right click on the project name MultiplyClient and create new web service client (New/Web Service Client). Select the MultiplyWS service in Project by using Browse.
  • Right click within main method of our Main.java class and select Insert Code/Call Web Service Operation and choose multiply from the available web service references.
  • Set the values of i and j and add in a code to print exception if you want.
  • Run the project and verify that the console printed the correct multiplication of i and j variables which we set in the previous step.
The process for creating the JSP or servlet-based client is the same, barring the fact that when we create a new project we choose File/New Project/Java Web/Web Application. We go through all the steps as above but we add the logic in a new servlet or a JSP and set the relative path in the project/properties/run accordingly to make these the entry points. Obviously the syntactic changes would be there to reflect that we are dealing with a servlet or a JSP when Insert Code/Call Web Service Operation happens. The only point worth mentioning is that the multiply operation can be dragged from the Web Service References to the appropriate point in the code to auto-generate the appropriate logic for the service call at that point. Thus for JSP we get this:



Experiment and enjoy!








Sunday, March 14, 2010

Command design pattern

The command pattern basically has client, command, invoker and the receiver. The pattern encapsulates request (command) as an object. It decouples the client from the receiver. The requests are defined through concrete commands which encapsulate the receiver and implement the command interface containing a single execute() method in it. It uses an invoker with a standardised interface (execute()) to invoke the request on the receiver. The invoker has no knowledge of the receiver. The concrete command it invokes knows about the receiver, the action to invoke on it and the parameters to be passed to it. We are basically issuing requests to objects without knowing anything about the receiver of the object or the method being invoked on it.

We will illustrate it with an example whose UML is in Fig1.


The walk through the example is self-explanatory.

package raj;

public class TestCommand {

public static void main(String[] arg) {
// First illustrate the tight coupling of Horse class
Horse horse = new Horse();
horse.eat();

/* Obviously we could do this with other classes too
* but we want to decouple the receiver of the action
* from the client using action commands invoked by an
* intermediary, the Invoker.
*/
// create the command we want to invoke
Command command = new EatCommand(new Horse());
// create the invoker
Invoker invoker = new Invoker();
// Tell the invoker about the command we want to execute
invoker.setCommand(command);
// execute the EatCommand via the invoker
invoker.execute();
// change the animal to tiger and execute
command = new EatCommand(new Tiger());
invoker.setCommand(command);
invoker.execute();
// illustrate how we can do no action
invoker.setCommand(new NoCommand());
invoker.execute();
// create a different type of command on a different class
// illustrate the action can do multiple things
invoker.setCommand(new ExamineCommand(new Vet()));
invoker.execute();
// pass parameters to command
invoker.setCommand(new PaperWorkCommand(new Clerk(), "Efficienly"));
invoker.execute();
}
}

interface Command {

public void execute();
}

class Invoker implements Command {

Command command;

public void execute() {
command.execute();
}

public void setCommand(Command command) {
this.command = command;
}
}

class NoCommand implements Command {

public void execute() {
}
}

class EatCommand implements Command {
/* the key thing is that the command knows about the receiver
* (contains Animal in this case)
* and the type of action to take on it (run eat() method)
*/

Animal animal;

EatCommand(Animal animal) {
this.animal = animal;
}

public void execute() {
animal.eat();
}
}

class ExamineCommand implements Command {

Vet vet;

ExamineCommand(Vet vet) {
this.vet = vet;
}

public void execute() {
vet.openSurgery();
vet.examine();
vet.closeSurgery();
}
}

class PaperWorkCommand implements Command {

Clerk clerk;
String efficiency;

PaperWorkCommand(Clerk clerk, String efficiency) {
this.clerk = clerk;
this.efficiency = efficiency;
}

public void execute() {
clerk.pushPaper(efficiency);
}
}

class Animal {

public void eat() {
System.out.println("Eating generically");
}
}

class Horse extends Animal {

public void eat() {
System.out.println("Eating grass");
}
}

class Tiger extends Animal {

public void eat() {
System.out.println("Eating meat");
}

public void attack() {
System.out.println("Killing a prey");
}
}

class Vet {

public void examine() {
System.out.println("Examine an animal");
}

public void openSurgery() {
System.out.println("Surgery opened");
}

public void closeSurgery() {
System.out.println("Surgery closed");
}
}

class Clerk {

public void pushPaper(String efficiency) {
System.out.println("Doing paperwork " + efficiency);
}
}

Note that strategy pattern had also encapsulated behaviour.


Saturday, March 13, 2010

Observer design pattern (Publisher-Subscriber)

The use of observer design pattern is ubiquitous in Java. We just have to consider Swing classes, GUI frameworks, RMI, JavaBeans etc to note its pervasive nature. Whenever a component registers for an action event, it is using the Observer pattern. The straightforward principle is that whenever multiple parties (observers) are interested in the changes of state of an object (subject/observable) then they subscribe for the notification of changes. The observable object monitors its state and on observing relevant change in its state, it notifies all the interested parties through a common update() interface. The subject provides methods for the subscription and un-subscription. Obviously, the subject can either push all the changes to the observers or allow the observers to pull the changes on notification through provides API. The key is that the subject and the observers are loosely coupled, as the subject has no knowledge of the observers.

Our sample program clearly illustrate the principle.

package raj;

import java.util.ArrayList;
import java.util.List;

public class TestObserver {

public static void main(String[] arg) {
// create the subject we are interested in subscribing
Subject subject = new Subject();
// create the subscriber for the subject
Bar interestedObserver = new Bar();
// add subscribers
subject.addObserver(new Foo());
subject.addObserver(new Bar());
subject.addObserver(interestedObserver);
// subject state changes; the observers notified
subject.stateChange();
// unsubscribe
subject.removeObserver(interestedObserver);
// check the unsubscribed party doesn't get further notification
subject.stateChange();
}
}

class Subject {

List observerList = new ArrayList();

public void addObserver(Observer o) {
observerList.add(o);
}

public void removeObserver(Observer o) {
int index = observerList.indexOf(o);
if (index >= 0) {
observerList.remove(index);
}
}

public void notifyObservers() {
for (Observer o : observerList) {
o.update("change");
}
}

public void stateChange() {
notifyObservers();
}
}

interface Observer {

public void update(String message);
}

class Foo implements Observer {

public void update(String message) {
System.out.println("Foo: " + message);
}
}

class Bar implements Observer {

public void update(String message) {
System.out.println("Bar: " + message);
}
}

We have opted for push technique in our example but it could be more appropriate to use pull as it allows the observer more flexibility in responding to the change.

Also it is worth noticing that Java provides its own implementation of Observer and Observable in the java.util package so the above sample could have been codes as:

import java.util.Observable;
import java.util.Observer;

public class JavaObserver extends Observable {
private String message;

public String getMessage() {
return message;
}

public void stateChange(String message) {
this.message = message;
setChanged(); // signifies state change
notifyObservers(message);
// the line below is for 'pull' as we pass the object so getMessage() can be invoked
// notifyObservers(this);
}

public static void main(String[] args) {
JavaObserver subject = new JavaObserver();
Baz bar = new Baz();
Baz baz = new Baz();
Baz foo = new Baz();
subject.addObserver(foo);
subject.addObserver(bar);
subject.addObserver(baz);
subject.stateChange("Change!");
}
}

class Baz implements Observer {
public void update(Observable o, Object message) {
System.out.println("Baz: " + message); // push
// the line below is for 'pull'
// System.out.println("Baz: " + ((JavaObserver) message).getMessage());

}
}

The key restriction of the Java built-in functionality is that we have to extend the Observable class so there is no way extending JavaObserver from any other class.







Model-View-Controller (MVC) pattern

The MVC architectural pattern is the bedrock of technologies like JavaServer Faces and is fundamental to implementing three-tier architecture. It clearly segregates the model in the business layer, view in the presentation layer and the controller, which handles all the inputs affecting the model. Obviously if the model is totally segregated then it becomes relatively easier to test the domain logic with automated tools. We can illustrate this decoupling of model and view through a simple calculator application which takes two numbers and applies the requested operator to provide the result.


package mvc;

import java.awt.event.ActionEvent;
import javax.swing.*;

public class MvcTest {

private static void buildUI() {
MvcModel model = new MvcModel();
MvcView view = new MvcView();
MvcControl control = new MvcControl("Result", view, model);
view.setControl(control);

JFrame frame = new JFrame("Test Calculator");
frame.getContentPane().add(view.getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
buildUI();
}
});
}
}

class MvcView {
// mainPanel holds all the GUI components

private JPanel mainPanel = new JPanel();
// two input fields and the result textfield
private JTextField firstOperand = new JTextField(10);
private JTextField operator = new JTextField(1);
private JTextField secondOperand = new JTextField(10);
private JTextField resultField = new JTextField(10);
private JButton addButton = new JButton();

public MvcView() {
resultField.setEditable(false);
operator.setText("+"); // default to add
mainPanel.add(firstOperand);
mainPanel.add(operator);
mainPanel.add(secondOperand);
mainPanel.add(new JLabel("="));
mainPanel.add(resultField);
mainPanel.add(addButton);
}

public void setControl(MvcControl control) {
addButton.setAction(control);
}

public JPanel getMainPanel() {
return mainPanel;
}

public String getFirstOperandText() {
return firstOperand.getText();
}

public String getSecondOperandText() {
return secondOperand.getText();
}

public String getOperatorText() {
return operator.getText();
}

public void setResultText(String text) {
resultField.setText(text);
}
}

class MvcControl extends AbstractAction {

private MvcModel model;
private MvcView view;

public MvcControl(String text, MvcView view, MvcModel model) {
super(text);
this.view = view;
this.model = model;
}

public void actionPerformed(ActionEvent e) {
view.setResultText(""); // clear the result
try {
double op1 = Double.parseDouble(view.getFirstOperandText());
double op2 = Double.parseDouble(view.getSecondOperandText());
char operator = view.getOperatorText().charAt(0);
if (operator == '+'
|| operator == '-'
|| operator == '*'
|| operator == 'x'
|| operator == 'X'
|| operator == '/'
|| operator == '%') {}
else throw new IllegalArgumentException();
double result = model.doOperation(op1, op2, operator); // use the model here
view.setResultText(String.valueOf(result));
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(view.getMainPanel(), "Only Numbers Allowed",
"Data Error", JOptionPane.ERROR_MESSAGE);
} catch (IllegalArgumentException nfe) {
JOptionPane.showMessageDialog(view.getMainPanel(), "The operator must be one of *, /, +, - or %",
"Data Error", JOptionPane.ERROR_MESSAGE);
}
}
}

class MvcModel {

public double doOperation(double op1, double op2, char operator) {
double result = 0;
switch (operator) {
case '+':
result = op1 + op2;
break;
case '-':
result = op1 - op2;
break;
case '*':
case 'x':
case 'X':
result = op1 * op2;
break;
case '/':
result = op1 / op2;
break;
case '%':
result = op1 % op2;
}
return result;
}
}

It is clear in our example that the view (MvcView) is the user interface which asks for two operands and the mathematical operation to apply on them. Model (MvcModel) is passed these inputs by the controller (MvcController) to get the calculation result. In our design the view has no knowledge of the model and the controller is an observer of the action performed on the 'result' button in the view. The controller uses its knowledge of the view to update the result. Thus a clear segregation of roles has been achieved. Obviously an application can have a number of these MVC triplets.






Friday, March 12, 2010

Factory design pattern

Let us give ourselves godlike powers and create a factory to produce animals. The basic structure for such a factory would look like:

package raj;

/**
* @author Rajeev
*/
public class AnimalFactory {
private String animalType;
AnimalFactory(String animalType) {
this.animalType = animalType;}

public Animal createAnimal() {
if (animalType.equals("Dog")) return new Dog();
else if (animalType.equals("Cat")) return new Cat();
else if (animalType.equals("Donkey")) return new Donkey();
else if (animalType.equals("Horse")) return new Horse();
else return new Animal();
}
}

class Animal {public String toString(){return "Animal";}}
class Dog extends Animal {public String toString(){return "Dog";}}
class Cat extends Animal {public String toString(){return "Cat";}}
class Donkey extends Animal {public String toString(){return "Donkey";}}
class Horse extends Animal {public String toString(){return "Horse";}}

It allows us to create an animal of a type which the factory has been geared to produce. We can test it with:

package raj;

/**
* @author Rajeev
*/
public class TestFactory {

public static void main(String[] arg) {
// create factories
AnimalFactory horseFactory = new AnimalFactory("Horse");
AnimalFactory dogFactory = new AnimalFactory("Dog");
AnimalFactory catFactory = new AnimalFactory("Cat");
AnimalFactory donkeyFactory = new AnimalFactory("Donkey");
AnimalFactory animalFactory = new AnimalFactory("");
// create horses
Animal animal = horseFactory.createAnimal();
Animal animal2 = horseFactory.createAnimal();
System.out.printf("We are type %s %s%n",animal,animal2);
// create dogs
animal = dogFactory.createAnimal();
animal2 = dogFactory.createAnimal();
System.out.printf("We are type %s %s%n",animal,animal2);
// create cats
animal = catFactory.createAnimal();
animal2 = catFactory.createAnimal();
System.out.printf("We are type %s %s%n",animal,animal2);
// create donkeys
animal = donkeyFactory.createAnimal();
animal2 = donkeyFactory.createAnimal();
System.out.printf("We are type %s %s%n",animal,animal2);
// create animals
animal = animalFactory.createAnimal();
animal2 = animalFactory.createAnimal();
System.out.printf("We are type %s %s%n",animal,animal2);

}
}

Now if we decide to produce 'sheep' in future or make a species extinct then all we have to do is to alter the Factory class to incorporate this new requirement at one central place. A demigod could be allocated a particular factory type now and he can happily go on churning objects of that particular species. This programming idiom is useful but not the Factory method pattern defined by GoF. Our current UML diagram is shown in Fig 1.


The GoF Factory method design pattern would alter the diagram to Fig 2.
With this variation, the TestFactory client is totally isolated from the realisation of the factory and its products (the concrete Animal). In this approach the client talks to the abstract interfaces which delegate the actual implementation to their subclasses. Our code changes accordingly to make this possible.

package raj;

public class TestFactoryFM {

public static void main(String[] arg) {
// create factory
AnimalFactoryIF horseFactory = new AnimalFactory("Horse");
// create horses
AnimalIF animal = horseFactory.createAnimal();
AnimalIF animal2 = horseFactory.createAnimal();
System.out.printf("We are type %s %s%n",animal,animal2);}
}

abstract class AnimalFactoryIF {abstract public AnimalIF createAnimal();}
class AnimalFactory extends AnimalFactoryIF {
private String animalType;
AnimalFactory(String animalType) {
this.animalType = animalType;}

public AnimalIF createAnimal() {
if (animalType.equals("Dog")) return new Dog();
else if (animalType.equals("Cat")) return new Cat();
else if (animalType.equals("Donkey")) return new Donkey();
else if (animalType.equals("Horse")) return new Horse();
else return new Animal();
}
}

abstract class AnimalIF { abstract public String toString();};
class Animal extends AnimalIF {public String toString(){return "Animal";}}
class Dog extends Animal {public String toString(){return "Dog";}}
class Cat extends Animal {public String toString(){return "Cat";}}
class Donkey extends Animal {public String toString(){return "Donkey";}}
class Horse extends Animal {public String toString(){return "Horse";}}

Hitherto, in our approach we have one-to-one relationship between the AnimalIF and its subclass and the FactoryIF and its subclass. However, the power of the approach becomes apparent if subclass our FactoryIF with another factory, SpecialFactory, which produces superior quality animals, SpecialAnimal, which are a subclass of the AnimalIF. The client is built to an interface and is totally unaware of the type of animal it is dealing with. Unsurprisingly, the Factory method design is used frequently in frameworks.

Compilation failures one should know in Java

Those of you who are preparing for SCJP are aware that nearly every question has 'compilation will fail' as an option. Here is a short random list of the compilation failures one should watch out for. No list of this nature can be comprehensive but it does include many useful hints.

while (false) {} // immediate error on the line
while (true) {}; // immediate error on the line following the loop
but while (true) {break;}
System.out.println(""); will compile.

throw new RuntimeException; // the line following is unreachable

go(1) when go(short i); // cannot down cast int to short have to say go((short) 1)

assert (): go(); where void go() // need a string and cannot have void

final X f = new X(); and then f=null; // cannot assign anything to reference
final int x=5; then x++ // especially with interface constants

importing static from a different package whose access is defined as default

We can define unused variables. It is not a compilation failure but just like unused imports.

switch case has a non-compile time literal (ie it is not defined and initiated final on the same line. It is not good enough to declare it as final on one line and then initialize it on the next).

You can't change the return type of overridden method, if return is int in parent then can't return Integer or short in the child. The temptation because of covariant returns is that it may be possible. An overridden method can return the child of a class defined in the parent. However it is a compile error to return parent to a child return type. If expecting Number m() return Integer; is fine, and Integer m() return Integer; is fine but Integer m() return Number; will not compile.

Calling super or instance from static block. Always ensure that an object exists in main before invocation of methods.

Using join, sleep or wait without handling InterruptedException or throwing InterrupedException from run(). The latter breaches the contract of Runnable interface by throwing an unexpected checked exception.

Method with no return type will not compile

new myrunnable().start will not compile. Has to be new Thread(myrunnable).start

class X is not correct nor is class

import static with just the class name fails

There is no such thing as super.super to invoke parent's parent.

You cannot override a static method with a non-static or vice versa.

try {} System.out.println("Here"); catch () {} will fail. No statements between try and catch.

parse needs to catch ParseException

run() cannot throw InterruptedException // no checked exception can be thrown which interface didn't define

for(String s:aa) // declaration has to be within foreach and s should not have been declared before. However it is OK to have s being used in multiple foreach as each has just the local scope.

assert 1 > 2: go(); // will not compile if from within main or any static block if go() not static

inner classes cannot have static members so be wary of their definitions.

import static java.lang.Integer.MAX_VALUE; then import static java.lang.Short.MAX_VALUE; as MAX_VALUE already defined.

declaring enum in a method fails

void doMore() {throw new IOException) fails becuase checked exception must say doMaore() throws IOException

If we catch Exception() then compiler won't allow any child of it to follow it. The order matters.

Putting long in switch expression, it can only be int or thing which can convert to in like char, byte, short

trying to use uninitialized local variable in a method or trying to prefix them with access modifier. Only valid modifier within method is final. Watch out for private int i = 5 in a method.

enum outside class can not be marked static, final, abstract, private or protected. Within the class it can be marked static, private or protected but not abstract or final.
myenum xx= new myenum(); won't compile. Enums are just initialised.

Trying to cast char into a String. char is a primitive and String is an object so S = c fails.

Instance variables cannot be marked strictfp, native, synchronized, abstract. final and transient are fine.

Not having a proper main() method is a runtime error, not a compiler error!

char c = -1; is illegal but char c = (char) -1 is OK. Char is unsigned integer literal with max value of 65535;

byte a = 3; byte b = 2; but byte c = a + b; will not compile as the result is an int. However byte c = 3 +5 is OK as within range and the compiler knows.

float f = 23.4; will not compile as 23.4 is a double.
A variable defined within the initialisation block is not visible to the program, ie {int j = 1;} j cannot be seen anywhere. Trying to use it later will not compile.

int i = 5; static {i = 7;} will not work as i is non-static.

You can't widen an Integer into a Long. The wrapper classes are different objects.

if (5 && 6) will not compile. The expression has to evaluate to boolean

if (x=6) is an illegal argument to if. It is just assigning. Can get away with this with boolean otherwise compile fails.

Integer i = new Integer(4); switch (i) is wrong if used as a case expression in switch statement.

continue statements must be inside a loop; otherwise, you’ll get a compiler error. break statements must be used inside either a loop or switch statement.

Labelled continue and break statements must be inside the loop that has the same label name; otherwise, the code will not compile.

Object test() { return (Double) 2.7;} works Object test() { return (Float) 2.7;} doesn't works 2.7 boxes to Double

Short n = new Short((short) 3); without the cast it fails. However it is ok to say Short s = 555; Integer i = 1 etc as long as they are within range.

More importantly it is fine to compare the incompatible wrapper types like Integer, Short etc with relational operators like greater than or greater than or equal to but not right to use ==. For relational comparisons of greater than, less than etc. it auto unboxes and doesn't complain.

boolean equals(Object o) {return true;} doesn't compile. hashCode(), toString() too are PUBLIC methods. As they are without public modifier they are improper override.

Watch out for missing semicolon in the definition of anonymous inner class.

The compiler will complain if you try to invoke any method on an anonymous inner class reference that is not in the superclass class definition.

Beware of sticking static in front of run() it will not compile as being improper override.

The public access modifier is the only one that allows code from outside a package to access methods in a package regardless of inheritance. If we are overriding a method in a subclass in a different package then the method must be public.

While using an interface from a different package, it must be declared public or we will not be able to use it. Just default package will not work.

Singleton design pattern

It is conceptually the simplest design pattern and many argue that it is actually an anti-pattern and continues to exist within computing courses because GoF specified it in their seminal work and it offers easy introduction to the subject of design patterns. Controversial it may well be but it has a useful purpose when we do genuinely need just one object of a class. Obviously the logger is the primary example.

The design is simple:

package raj;

class TestSingleton {
public static void main(String[] arg) {
Singleton s = Singleton.getInstance();
System.out.println(s.toString());
s.setVal(100);
Singleton s2 = Singleton.getInstance();
System.out.println(s2.toString());
System.out.println(s2.getVal());
}
}

public class Singleton {

private static Singleton singletonObj;

private Singleton() {
}
private int val = 0;

public int getVal() {
return val;
}

public void setVal(int val) {
this.val = val;
}

public static Singleton getInstance() {
if (singletonObj == null) {
singletonObj = new Singleton();
}
return singletonObj;
}
}

It relies on having a private constructor and public static interface to provide the object. We can make this design thread-safe by synchronizing the getInstance() method:

public static synchronized Singleton getInstance() {
if (singletonObj == null) {
singletonObj = new Singleton();
}
return singletonObj;
}

However, this approach would considerably slow down the access to the object as synchronization can be painfully slow and is only needed during the first create. To over come this we may eschew lazy instantiation of the object and change our Singleton class to the following to let the class loader take the responsibility for instantiation:

public class Singleton {

private static Singleton singletonOb = new Singleton();j;

private Singleton() {
}
private int val = 0;

public int getVal() {
return val;
}

public void setVal(int val) {
this.val = val;
}

public static Singleton getInstance() {
return singletonObj;
}
}

This is great! But if the objected created is a scarce resource and is never used then it obviously is wasteful. A thread-safe compromise solution would be to use double-checked locking:

public static Singleton getInstance() {
if (singletonObj == null) {
synchronized (Singleton.class) {
if (singletonObj == null) singletonObj = new Singleton();
}}
return singletonObj;
}

Now we take the synchronization hit just during the create but there is still a small overhead of an extra conditional check during every access. Also note that we cannot use synchronized(this) as we are locking from within a static context so need the class literal Singleton.class.

Thursday, March 11, 2010

Decorator design pattern

When a computer manufacturer like Dell is confronted with a scenario of supplying basic computer with various add-ons, how does it provide the correct description for the configuration and its correct price? One option would be to create a Computer class and then subclass it with each variant like ComputerPlusWindows, ComputerPlusWindowsPlusExtraMemory etc. We can already see the classes proliferating and the nightmare gets worse when the price of a component changes as it would need to be reflected in each configuration using the changed price. Here the utility of Decorator design pattern becomes evident as we can can create wrapper classes for the variants which HAS-A computer. The trick is to create an abstract decorator for our original Computer class and let all the variant classes extend this decorator while wrapping themselves around the Computer class. In our example below, we have taken a basic Computer with price and description and created just two variants of Windows7Computer and ExtraMemoryComputer to correctly reflect the name of the add-on and the price with the add-on.

package raj;

/**
* @author Rajeev
*/
public class DecoratorTest {
public static void main(String[] arg) {
Computer computer = new Computer();
// put windows 7 wrapper
computer = new Windows7Computer(computer);
System.out.println(computer.getDescription());
System.out.println("Cost "+ computer.getPrice());
/* Basic computer + Winodws 7
Cost 230.75
*/
// put extra memory wrapper
computer = new ExtraMemoryComputer(computer);
System.out.println(computer.getDescription());
System.out.println("Cost "+ computer.getPrice());
/* Basic computer + Winodws 7 + 2G memory
Cost 281.5
*/
// put more extra memory
computer = new ExtraMemoryComputer(computer);
System.out.println(computer.getDescription());
System.out.println("Cost "+ computer.getPrice());
/* Basic computer + Winodws 7 + 2G memory + 2G memory
Cost 332.25
*/
}
}

class Computer {

private String description = "Basic computer";
private double price = 200.50;

public String getDescription() {
return description;
}

public double getPrice() {
return price;
}
}

abstract class ComputerDecorator extends Computer {

public abstract String getDescription();

public abstract double getPrice();
}

class Windows7Computer extends ComputerDecorator {

Computer computer;
private double price = 30.25;
private String description = "Winodws 7";

public Windows7Computer(Computer computer) {
this.computer = computer;
}

public String getDescription() {
return computer.getDescription() + " + " + description;
}

public double getPrice() {
return computer.getPrice() + price;
}
}

class ExtraMemoryComputer extends ComputerDecorator {

Computer computer;
private double price = 50.75;
private String description = "2G memory";

public ExtraMemoryComputer(Computer computer) {
this.computer = computer;
}

public String getDescription() {
return computer.getDescription() + " + " + description;
}


public double getPrice() {
return computer.getPrice() + price;
}
}

Now we can see that we can create variants of adding anti-virus, extra CD, network card etc and the wrapping works perfectly. In our design, it would have been better to put the reference to Computer in the ComputerDecorator then the concrete subclasses of Decorator but the net effect is the same. Incidentally the classes in java.io package pertaining to various streams and readers/writers use this pattern extensively. Whenever we need to add-on extra behaviour dynamically then Decorator is the answer.

Strategy design pattern

Here is a bit of code which illustrates the Strategy Design Pattern:

package raj;

/**
*
* @author Rajeev
*/
public class StrategyTest {

public static void main(String[] arg) {
Animal dog = new Dog();
Animal cat = new Cat();
Animal donkey = new Donkey();
Animal trickDog = new TrickDog();
dog.makeNoise();
cat.makeNoise();
donkey.makeNoise();
trickDog.makeNoise();
}
}

class Animal {

Noise n;

void makeNoise() {
n.makeNoise();
}
}

class Dog extends Animal {

Dog() {
n = new WoofNoise();
}
}

class TrickDog extends Animal {

TrickDog() {
n = new MeowNoise();
}
}

class Cat extends Animal {

Cat() {
n = new MeowNoise();
}
}

class Donkey extends Animal {

Donkey() {
n = new BrayNoise();
}
}

abstract class Noise {

abstract void makeNoise();
}

class BrayNoise extends Noise {

void makeNoise() {
System.out.println("Bray");
}
}

class WoofNoise extends Noise {

void makeNoise() {
System.out.println("Woof");
}
}

class MeowNoise extends Noise {

void makeNoise() {
System.out.println("Meow");
}
}

The key things is that rather than overriding the makeNoise() method of Animal class in all the subclasses we have abstracted out this behaviour in a separate class as it has a number of variations. The Animal class now HAS-A relationship with this Noise algorithm. All the subclasses of Animal set the proper Noise behaviour in their constructor. This allows our TrickDog to magically start meowing. Also this new Noise class can be used in other situations where appropriate.

Also note that rather than using abstract class for Noise we could have defined it as an interface and then implement it in our concrete Noise classes. The logic becomes:

abstract interface Noise {
abstract void makeNoise();
}

class BrayNoise implements Noise {
void makeNoise() {
System.out.println("Bray");
}
}

... and so on.



Friday, January 29, 2010

Things to watch out for Java novices


In the process of learning Java one encounters many points to which a novice should pay special attention. Doing Sun tutorials obviously helps people to come to grips with some of these points but some salients points have been highlighted here in random order.
No constructor can have a return type (not even void).
We can override a private member of a superclass in the subclass with a private/public/protected member. Effectively it is not override as subclass is not even aware of the superclass private member and sees it as a new definition. The rules of overriding do not apply, so you can make this newly-declared-but-just-happens-to-match method declare new exceptions, or change the return type, or anything else you want to do with it.
No modifier means method has default access. Default is similar to protected. However in protected subclass can be in different package but in default access it has to be in the same package.
default = package; protected = package+subclasses access.
Protected member can be accessed through inheritance but not not through access to an instance of parent object, if it is in a different package. Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass.
There is never a case where an access modifier can be applied to a local variable. It will not compile. We can only use 'final' modifier for local variables.
A reference variable marked final can’t ever be reassigned to refer to a different object. The data within the object, however, can be modified, but the reference variable cannot be changed. There are no final objects, only final references.
If you declare a final instance variable, you’re obligated to give it an explicit value, and you must do so by the time the constructor completes.
Static methods can’t be overridden, they are hidden.
You can put as many classes in a source code file as you like, but only one (or none) can be public. The file name should match the name of the public class, but if no public class is in the file, you can name it whatever you like. The order in which the classes appear makes no difference.
Not having a proper main() method is a runtime error, not a compiler error!
All variables defined in an interface must be public, static, and final, ie only constants. If we don't give these modifiers or give only part of them, they are automatically given these three characteristics.
An interface is free to extend multiple interfaces.
An inner class instance has access to all members of the outer class, even those marked private.
Just because a series of threads are started in a particular order doesn't mean they'll run in that order.
sleep() and yield() static methods always affect the thread that's currently executing and not another thread.
If a thread goes to sleep, it holds any locks it has—it doesn't release them.
Default exception handler
– Provided by Java runtime
– Prints out exception description (e.getMessage())
– Prints the stack trace (e.printStackTrace()) , ie hierarchy of methods where the exception occurred
– Causes the program to terminate
Collections.disjoint(l1, l2) — determines whether two Collections are disjoint; that is, whether they contain no elements in common.
All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
The constructor for an enum type must be package-private or private access.
An enum cannot be declared within a method.
As an inner non-static class is associated with an instance, it cannot define any static members itself. An inner class must be static to be called from static method.
Polymorphism doesn't apply to static methods.
Polymorphism only applies to instance methods and not instance variables
System class maintains aProperties object that describes the configuration of the current working environment. To maximize portability, never refer to an environment variable (extracted from System.getnnv) when the same value is available in a system property (extracted from System.getProperties). Use latter value.
For example, to get the value of path.separator, use the following statement: System.getProperty("path.separator");
System.exit, which terminates the Java virtual machine with an exit status, invokes SecurityManager.checkExit to ensure that the current thread has permission to shut down the application.
By convention, an exit status of 0 indicates normal termination of the application, while any other value is an error code.The exit status is available to the process that launched the application.
All byte stream classes are descended from InputStreamand OutputStream.
All character stream classes are descended from Readerand Writer.
To use line-oriented I/O use two classes BufferedReader andPrintWriter. Latter is used in servlets.
Channel I/O reads a buffer at a time.
There are four buffered stream classes used to wrap unbuffered streams:BufferedInputStream andBufferedOutputStream create buffered byte streams, whileBufferedReader andBufferedWritercreate buffered character streams. They improve I/O performance.
When you need to create a formatted output stream, instantiate PrintWriter, notPrintStream.
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int,long,float, and double) as well as String values. All data streams implement either theDataInput interface or theDataOutput interface.
Just as data streams support I/O of primitive data types, object streams support I/O of objects.
Using a int as a return type on byte input stream allows read()to use -1 to indicate that it has reached the end of the stream. We can use (char) cast to see the value of int read, ie int 65 is same as 'a' after cast. For line-oriented I/O use inputStream.readLine() != null to detect end of file.
Notice that DataStreamsdetects an end-of-file condition by catching EOFException, instead of testing for an invalid return value.
When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array of values. The vararg has to be the last argument and there can be only one vararg.
String s = "Java"; s.concat( " Rules); System.out.println(s); will give 'Java' not 'Java Rules' as the output of s.concat(0 is not placed in our reference for s. To get 'Java rules' we have to say s = s.concat(). Without this syntax the newly created string has no reference. In the case of StringBuffer sb, sb,.append() will append the value without assigning to the reference.
Static variables are never saved as part of serialisation as they belong to class and not object.
If serializable subclass is serialised and parent is non-serialiazable then parent will have initial values as per creation of new object.
When using classpath the last directory in the classpath must be the super-directory of the root directory of the package, ie if package is com.my... then the classpath should have directory which has com as subdirectory.
Put jar file in jre\lib\ext and java finds it without specifying in classpath.
Static imports can be used when we want to use a class's static members.
Collection (singular) is an Interface, but Collections (plural) is a helper class.
equals() returns false if the wrapper object types are different. It does not raise a compiler error.
No inner class (non-static inner class) can have a static member.