Wednesday, December 30, 2009

HTML: Definition, <hr>, Heading, <code> <span> <div> Tags

Definition Tag

The common way to show a Definition is to use the definition tag <dl>

For Example:
<dl><dt>Newton's 3rd Law</dt><dd>every action has equal and opposite reaction</dd></dl>
will be displayed as
Newton's 3rd Law
every action has equal and opposite reaction


Alternatively, you can place a Definition between horizontal lines using the <hr> tag as follows:


Newston's 3rd Law: Every action has equal and opposite reaction
Code:
   <blockquote><hr><strong>Newton's 3rd Law</strong>: Every action has equal and opposite reaction<hr></blockquote>

Heading Tags

There six heading tags in HTML starting from <h1> to <h6> in the descending order of there sizes respectively. <h1> being the largest while <h6> is the smallest.

<code> Tag

This tag is generally used for souce-code. It is just a variation from the normal text size
Example:
   <code>text from source-code</code>
will be displayed as
   text from source-code

<span> <div> Tags

Both <span> and <div> are similar, to the extent that both can apply styling to a block of texts. But <div> tag can do more than that. <div> tag can be used to make logical divisions within an HTML document. The <div> tag automatically breaks paragraphs, hence each <div> creates a separate division. Different stylings can be performed on each division. The <span> tag can only apply a particular styling to the section enclosed within the tag. No formatting is done by the <span> tag.


Reference Links:
Definition Tag
<HR> Tag
Headings
<span> and <div> Tags

Exceptions

Exception
is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions
When an exception occurs, an exception object, is created which consists of information about the error. This process of creating an exception object during runtime is called throwing an exception. An appropriate exception handler is chosen to handle the exception. This is called catching an exception

Any Java programming language code must honor the Catch or Specify Requirement. That is, a set of instructions that can throw exceptions must by follow either of the following two rules:
  • A try statement that catches the exception. The try must provide a handler for the exception
  • A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception.

Kinds of Exceptions

  1. Check Exceptions: These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose the application accepts an array of integers from the commandline, but if the number of integers exceed the array size limit defined in the program then the application should prompt the user to re-enter correct number of integers. Checked Exceptions are subject to Catch or Specify requirement while other exceptions do not comply.
    RuntimeException, and their subclases.
  2. Error: These are conditions that occur external to the application. Hardware failures is the best example of such conditions.
  3. Runtime Exception: These are internal application faults that the application cannot anticipate. These usually indicate programming bugs. Rather than catching these exceptions and handling them it is better to eliminate the bug that caused the exception to occur.

try, catch and finally blocks

try block
it contains the code that might throw an exception
. try block can enlcose a single line of code that might throw an exception or a full block of method.
catch block
it contains the code required to handle an exception thrown from a try block.
Multiple catch blocks can exist based on the number exception thrown from a try block. The first catch block must immediately follow the try block.
finally block
it contains code, that always executes when the try block exits.
The finally block is very useful to cleanup used resources for furthur re-use. A catch is only an option to specify when a finally block is specified

Specifying Exceptions with the throws Clause

If we do not want to specify a catch block(s) for the exceptions occurring in a method, but would like some method higher in the call stack to handle it, then we can just specify the type of exceptions the method throws in the method declaration itself.
Example:
   public void writeList() throws IOException, ArrayIndexOutOfBoundsException {
Since, ArrayIndexOutOfBoundsException is an unchecked exception, including it in the throws clause is not mandatory.

throw Statement

Inorder, to catch an exception object, it should be thrown at the first place. The throw keyword is used by methods, in this context, to throw exception objects.
Example:
   if(size == 0){
      throw new EmptyStackException();
   }
The above example, is a code taken partly from the pop() method of common stack object. Here, if the size of the stack is empty it throws an object of EmptyStackException() exception class.

Throwable Class

All exception-objects are objects of Throwable class or its subclasses. Error and Exception are the first descendants of throwable class.

Chained Exception

An exception can throw another exception, hence forming a chain of exceptions. This is possible, in general by throwing an exception inside a catch block. The following methods and constructors in Throwable support chained exceptions:
  • Throwable getCause()
  • Throwable initCause(Throwable)
  • Throwable(String, Throwable)
  • Throwable(Throwable)
The Throwable arguement to initCause() method the Throwable constructors is the exception that caused the current exception. getCause() method returns the exception that caused the current exception.

Stack Trace Information
Stack Trace
it provides information on the execution history of the current thread and lists the names of the classes and methods that were called at the point when the exception occurred.
Using the getStackTrace() method on the exception object will allow you to know the source of exception chain.

Creating Exception Classes

The Java Platform, provides a wide range of exception classes for use. If for any purpose, you require your own exception class
related to the program then you can manually create. All exception-classes can inherit any of the subclasses of Exception class. But it would be more appropriate to inherit Exception only.


tutorials

Tuesday, December 29, 2009

Packages in JAVA

Packages are used, to allow re-use of names. A package consists of classes and interfaces. It is a grouping of related types providing access protection and name space management. Common reasons to bundle classes and interfaces in a single package are:
  • Everyone can easily determine that these types are related
  • Locating types that can provide a specific functionality is easy
  • Names can re-used. That is, a single package is a single namespace.
  • Access priviledges can be set for complete access within the package but zero access outside the package.

Java platform comes with innumerable number of packages. The most fundamental among them are java.lang and java.io.

Creating a Package

This is as simple as choosing a naming as per the convention and putting this name along with the package statement in every source-file that is included in the package. The package statement looks like this:
package networking;
In the above statement 'networking' is the name of the package. The package statement should always be the first statement in a source-file followed by class definitions.

Naming Conventions

In package names all letters are in lower-case. Packages the come with JAVA platform begin with either java or javax. Packages created by outside companies generally use their domain names in reverse order as a prefix. For example, com.company.package is the fully-qualified name of a package created by a company whose webaddress is www.company.com

Accessing Package Members

Public members inside a package can be accessed by any of the following methods:
  • Refer to the member by its fully qualified name
  • Import the package member
  • Import the member's entire package

Miscellaneous

  1. Most of the package-names look as if there are in some hierarchy, but in fact all are nothing but different packages. For example, java.awt is a package of its own while java.awt.color and java.awt.font are different packages of there own.
  2. If the two packages, having similar classnames for two or more classes are imported, then the qualified name of the class should be used.
  3. Static Import statement can be used to avoid prefixing the static member calls with the classnames.


tutorials

Subtyping

In java, its a feature, where an object of subclass be assigned to an object of its superclass.
Number myNumber = new Number();
Long telephoneNo = new Long(27000134);
myNumber = telephoneNo;

Similarly in the case of method calls, a sub-class object can be passed as a parameter to a method, that is has a super-class object as a parameter in its defination.
public void someMethod(Number n){
   ......
}

someMethod(new Integer(10));
someMethod(new Double(10.1));
The above feature can also be implemented using generics as follows:
Box box = new Box();
box.add(new Integer(10));
box.add(new Double(10.1));


tutorials

Generics

Generics can be compared with Class Templates in C++ programming. It is implemented to generalise the code for all data-types. That is, a single method definition can be used for different data-types and classes. Considering the following class, Box as an example for understanding Generics.
public class Box<T>{
   private T t; // T stands for "Type"

   public void add(T t){
      this.t = t;
   }
   public T get(){
      return t;
   }
}
The above generic class, Box, is used to store an object of a particular type, inside it. That is, an integer Box can store only an integer variable. Similarly, a String Box can store only a String object. The T in the class is replaced appropriately with a classname or type-name used in class instantiation.
Box integerBox = new Box();
Click here, to check out the non-generic version of the Box class.

Type Parameter Naming Conventions

By convention, type parameter names are single, uppercase letters. The most commonly used type parameter names are:
  • E - Element
  • K - Key
  • N - Number
  • T - Type
  • V - Value
  • S,U,V etc. - 2nd, 3rd, 4th types


Generic Methods and Constructors

Let us understand this, with the help of a generic method definition inside the above generic class Box
public class Box<T>{
   .....
   .....
   .....

   public <U> void inspect(U u){
      System.out.println("T: " + t.getClass().getName());
      System.out.println("U: " + u.getClass().getName());
   }
}
Now, let the class be instantiated, as an Integer type. If we invoke the method, with the following line of code:
inspect("some text");
then the output is:
T: java.lang.Integer
U: java.lang.String

Bounded Type Parameters


The extent of generality imposed on a class or a method can be restricted to some classes or types. This is achieved with the help of extends keyword. Suppose, if you want a method to be used only with instances of Number class, then, the method can be defined as:
public <U extends Number> void inspect(U u){
   ..........
}
This method can now be invoked by an object of Number class or its sub-classes. To specify additional interfaces that must be implemented, used '&' character.

Wildcards

In JAVA, unknown types can also be represented in Generics with the help of wildcard character "?". Unknown types, with either upperbound or lowerbound can be specified as follows:
Cage<? extends Animal> someCage = ...; // here Animal class is the upperbound
Cage<? super Animal> someCage = ...; // here Animal class is the lowerbound
Now consider, Lion and Butterfly to be subtypes of Animal. If, Cage<Animal> is defined as a cage to hold all animals, then Cage<Lion> is for lions and Cage is for butterflies. Now, if we see logically, it appears that Cage and Cage<butterfly> are subtypes of Cage<Animal>, but reality Cage<Lion>, Cage<Butterfly> and Cage<Animal> are all subtypes of Cage<? extends Animal>. This is because, Cage<Animal> is not a generic class, but infact a specification of generic class Cage<? extends Animal>. Click here, to understand wildcards more clearly.

Unbounded Wildcards are just defined with '<?>'

Type Erasure

Some of the operations given below are not possible with Generic classes:
  • if(item instanceof E)
  • E item2 = new E();
  • E[] iArray = new E[10];
  • E obj = [E]new Object();
This is because, when a generic type is instantiated, the compiler removes all information related to type parameters and type arguments within a class or method. Hence, any operation that includes knowing the type or modifying the type cannot be performed. This process of removing the type information is called, Type Erasure.

tutorials
subtyping


Reference Links:
C++ Class Templates

Strings in Java

The String class, is one of the special classes in Java. It's is high utility class.

A String object can be created in many ways, with the help of the many constructors of String class. The most simple methods are:
String greeting = "Hello world!";

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);

Some useful features of String are:
  • String Length: The length of String or the number of characters in the String object can be known easily with help of length() method.
  • charAt() method: The charAt(int index) is used to return the character at a specific location in a String.
  • getChars() method: The getChars() method is used to convert a string or substring into a character array.
  • Concatenating Strings: Two strings can be joined to one string in the following ways:
    1. String1.concat(String2);
    2. "My name is ".concat("Rumplestiltskin");
    3. "Hello," + " world" + "!"
  • Creating Format Strings: The String class has a static format() method, that allows you to create a formatted string that can be re-used.
    Example:
       String fs;
       fs=String.format("The value of the float variable is %f, while the value of the " + "integer variable is %d, and the string is %s", floatVar, intVar, stringVar);


tutorials

Monday, December 28, 2009

2 Methods to Convert a Number in String into Integer

When taking integer values from the command-line, the numbers are stored in String argument args[] which is given as a parameter to the main() method.


In the above image, the numbers in the yellow box are the parameters to the main() method

To convert, numbers in String format into int or float datatype, we have the following 2 methods.

Method 1: Using parseInt() method
The parseInt( String s )" method, converts the given number in string s into an Integer. This number can now be assigned to variable of int datatype or object of Integer class.

Similarly, we can use parse methods for Float, Double etc.

Note: parseInt() method and similar methods in Float, Short etc are static methods, hence there should be called with corresponding Classname as prefix to there method-call

Method 2: Using valueOf() Method
This is another static method. It is also available in datatypes other than Integer
Syntax:
   (Integer.valueOf( String s ).intValue())
The intValue() method is used to return the value of Integer object as int

Saturday, December 26, 2009

My First Java Swing based Application Part II with Modifications

Now, we have rough outline of the application as shown before, but due to the requirement of new features, some modifications have been made to the GUI.

Modification 1:
A new JTextField and JLabel have been added to input book publisher data. They have been named as publisherTF and publisherLabel respectively.

Modification 2:
One new JButton has been added to clear the contents of the textfield's. The JButton, has been appropriately named as "Clear".

Modificaiton 3:
The radiobuttons, under Delivery Time have been renamed from '7-14 working days' and '20 working days' to '7-15 working days' and '20-30 working days' respectively.

Modification 4:
The overall dimensions of the JFrame have been modified to fit the needs of application. The width of all the textfields, and placement of the other components also are adjusted as per the requirement.

Designing the Code Logic
To design the logic of the application, let us understand the purpose of the application once again, clearly.

The program is designed to format the given inputs about a book, into a book description in HTML format. This HTML template will be used for display in Ebay India website.

Now, let us outline all the inputs about the book, that we are going to consider in our application
  1. Title
  2. Author(s)
  3. ISBN-10
  4. ISBN-13
  5. Pages
  6. Publisher
  7. Format
  8. Publisher's note or Book Description &
  9. Delivery Time
All the above inputs, will be added in corresponding locations within the HTML template and the completed HTML code will be generated in the Description TextArea on pressing the Generate button.

Placing the Inputs
To place the inputs, appropriately in a given location in HTML document, I have created a new class called DescriptionParts, that consists of a set of strings. These strings are parts of the whole HTML code formatted, minus the inputs. When all the strings are combined in a specified order along with the inputs, we get the complete HTML code which can be used on the website. The process of combining the inputs with the HTML code is done on clicking the Generate button. The combining process is done with the help of StringBuilder object. With the help of StringBuilder's append() method, a final string(completed HTML code) is built.
  • The Strings in Description Parts are broken appropriately, so that the inputs from the GUI are placed correctly
  • When the Generate button is clicked, append calls are made one after the other to add the Strings and inputs.
finalCodeObject.append(DescriptionPartsObject.anyStringVariable);
finalCodeObject.append(JTextFieldObject.getText());
The above syntaxes are used for appending strings from DescriptionParts and from inputs respectively, one after the other.

Absence of Data
If due to any reason. some textfields namely publisher, format & ISBN-10 are not filled, then the application will built the final book description by omitting these fields. To program this logic, I am using length() method of String class, to check if the textfield is empty or not. The syntax for coding this is:
if( textFieldObject.getText().length()!= 0 ){
.........
}


Event Actions
Generate Button
In the above image, you can see part of the code, that is used for appending strings from DescriptionParts and Data Inputs from the text-fields. All this code is defined in the method generateButtonActionPerformed(java.awt.event.ActionEvent evt). This method runs, only when the generate button is clicked.
To reach this method in the source-code directly from the design interface, follow the steps below
  • Right-click on the generate button,
  • Then, move the mouse cursor over events,
  • Next, select Action &
  • Finally, click on Action Performed

ClearButton
The 'Clear' button is used to clear the contents of the textfields. The clearButtonActionPerformed() method, assigns all text-fields to null, using the JTextComponent's setText() method.
Syntax:
   jTextFieldObject.setText(null);

The Clear button also, sets the delivery time to 7-15 working days by default.

Delivery Time RadioButtons
The 2 radio buttons used for Delivery Time should be mutually exclusive. That is, when one button is selected the other should be deselected. This is implemented by coding the selection and deselection logic in the actionPerformed() methods of the respective radio-buttons.

The Constructor
  • Initializes the GUI components
  • Selects 7-15 working days (Delivery Time) radio button


Reference Links:
My First Java Swing base Application

Friday, December 18, 2009

HTML Snippet: <img> Tag Attributes

The <img> tag is used for placing images in a HTML document. The <img> tag has many style properties. "display" is one important property, that is commonly used. When 'display' is assigned with the value of 'block', the img tag, will generate a block box with a line break before and after the element. The box contains the image. The following image illustrates the above:

HTML Code:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxgEJdK7q11m-vjCu74yKCSqrjdyf3P7ou502lLwOt5oxtGH0uqZpeP71HIDoDQQ12sKMW5f6uLd766FrShVPT2GitxTvfZsBsqDgnhiCRcryGf2R1yKaJcIspCi9f6pUeujkGV0nd81Tr/s1600-h/a+r+rahman+the+musical+storm.jpg"><img style="display:block; margin:0 auto 10px;cursor:pointer; cursor:hand;width: 150px; height: 196px; " src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxgEJdK7q11m-vjCu74yKCSqrjdyf3P7ou502lLwOt5oxtGH0uqZpeP71HIDoDQQ12sKMW5f6uLd766FrShVPT2GitxTvfZsBsqDgnhiCRcryGf2R1yKaJcIspCi9f6pUeujkGV0nd81Tr/s320/a+r+rahman+the+musical+storm.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5416612633228985058" /></a>
Similarly, "float" is another important property used to place an image on the left or right side while having a text of paragraph wrap around it. 'float' can take only two values either left or right.

HTML Code:
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpL4JOQLo5DjpCgWUmhSsuaELjWDIn7vPY-xuL_zJqbTftf6vFEYSGwoC1tFgaZSTLSaXSjxcoXsInZPtCI9b_Di9JIhYcZaSGk5U1VgrMy2vuGfSGEsEDeCPpLYRAjd3t-dQhHQVra-ti/s1600-h/float+right.jpg"><img style="display:block; margin:0px auto 0; text-align:center;cursor:pointer; cursor:hand;width: 315px; height: 219px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgpL4JOQLo5DjpCgWUmhSsuaELjWDIn7vPY-xuL_zJqbTftf6vFEYSGwoC1tFgaZSTLSaXSjxcoXsInZPtCI9b_Di9JIhYcZaSGk5U1VgrMy2vuGfSGEsEDeCPpLYRAjd3t-dQhHQVra-ti/s320/float+right.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5416615662073713282" /></a>
In the above image, the "css" image is floating on the right side.


Margins can be specified around an image with the help of <margin> property. <margin> can be used in a variety of ways. Generally, <margin> is specified with 4 values - top, right, bottom, left. The values are specifed either in pixels or percentages. margin can be loaded with only 2 values also - the first value represents top & bottom while the second represents left & right. <margin-left>, <margin-right>, <margin-top>, <margin-bottom> can be used individually to specify margins for each side individually.

Reference Links:
CSS: margin
CSS: float
img tag
CSS: display

My First Java Swing based Application

The purpose of this application, is to format book descriptions in a prescribed HTML template for listing in Ebay. To this, I will be designing the app using Java Swing components with help of Netbeans IDE.

Since this is my first project that I would like to seriously complete, I have decided to use the Celsius Converter project in the Java Tutorials as a reference example.

Project Creation
Created a New project(General Java Application) with the name BookDescription. Unchecked the 'create main class' option as suggested in the CelsiusConverter project. On clicking the finish button the project was created

Create New JFrame
After successful creation of the project, the project name BookDescription appears in the Project window towards the extreme left. Now right-click on the project name, then click on 'New' and select 'JFrame Form'. A new JFrame appears in the project window.



Entering a Title Name
Select JFrame in the inspector window. Now in the Properties window at extreme right, single-click on the empty box against the 'title' property and enter the title name as Book Description.





Placing the Components
Place the swing components, by dragging them one after the other from the pallete window at the top right corner, into the JFrame. The list of components required for this project are:
  • JTextField - 6
  • JLabel - 5
  • JRadioButton - 2
  • JButton - 1
  • JTextArea - 1
. Now, adjust the components in the required position and also resize them. If you see now, the components are named as JTextField1, JLabel1, JLabel2, JTextArea... etc which is not we want. Hence, rename appropriately with suitable names based on the project requirement. To rename, simply right-click twice on the components adn then rename. Care should be taken, while removing text from JTextField, as the component will get compressed when text is removed. If you do not want to display any text in JTextField, resize them accordingly.


Understanding the Components
  1. Title: The Title of the book
  2. Author: The Author(s) of the book
  3. ISBN-10: The 10 character International Standard Book Number.
  4. ISBN-13: The 13 digit International Standard Book Number.
  5. Pages: Number of pages
  6. Format: The bound of the book either paperback or hardcover
  7. Delivery Time: Number of days required for shipping the book - either 7-8 days or 14 days
  8. Description: Text-area for inputting publisher's description about the book and outputting HTML code also
  9. Generate: To generate HTML code for the formatted document

Renaming of Component Variable Names

Now that the form along with the components in it are ready, we can go ahead with coding the logic for the application. But before doing it, we need to change the Variable Names of each component, which will be effected in coding. This can be done from the inspector window. Initially, all the components have common names such as JTextField1, JTextField2, JLabel1... etc with there typename, in the square brackets on the right side. To change the variable name just right-click on each of them and then select Change Variable Name... as shown in the image.