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.

Saturday, November 21, 2009

Convert Base5 number to Decimal

The following is the code to convert a base 5 integer into decimal number. This program, can also be used to convert a number in other number systems to decimal number system. The conversion is performed by the valueOf() method of the Integer class.
public class Base5Demo {
public Integer convertBase5( String number ){
Integer x;

x = Integer.valueOf(number, 5);
return x;
}

public static void main(String args[]){
String num = "230";
Base5Demo base5 = new Base5Demo();

System.out.format("%d",base5.convertBase5(num));
}
}


In the above program, intially the number is stored in string 's'. 's' is in the number system represented by the integer 5, i.e, base 5 number system. This integer is called radix.

The output of the above program is: 65(230 in base5 system).

Binary to Decimal
The above program can be tried for binary number conversion also. A program for this purpose would be as follows:
public class convertBinaryDemo {
public Integer convertBinary( String number ){
Integer x;

x = Integer.valueOf(number, 2);
return x;
}

public static void main(String args[]){
String num = "0110";
convertBinaryDemo bin = new convertBinaryDemo();

System.out.format("%d",bin.convertBinary(num));
}
}


Output: 6

Wednesday, November 18, 2009

Basics: Static Import

Static members of a class are called by prefixing their names with a period (.) operator and then the class name.
Classname.methodName(arguments);
If a program requires many static members from a single class, then static import feature can be used, to avoid prefixing the classname when calling the class members

Consider the Math class, which has many static members. By adding the following code, you don't have to write Math in front of every math class member.

tutorials

Tuesday, November 17, 2009

HTML Snippet: Anchor 'NAME'

The name attribute of anchor ( <a> ), creates a named anchor in a HTML document. This allows, direct navigation to any location in a HTML document, from external URLs. It also allows for, easy reading of long documents.

For example, to reach the bottom of a HTML page, the following code is written at bottom
Usage:
    <a name='Bottom'></a>
The Syntax of the URL to reach this location is

http://---complete URL----/#Bottom

Numbers in JAVA

In JAVA programming, numbers can be used as primitive data types or objects as well. This is done with the help of Number class. The number class is the parent class for Byte, Integer, Float, Double, Long and Short classes. All these classes are called wrapper classes, because they wrap the primitive values - at places where they are required as an object.
For example, considering the following code:
Integer x, y;
x=12;
y=15;
In the above code, x and y are Integer objects assigned with primitive int values. When compiling this code, the compiler wraps them into Integer objects. Similarly, unwrapping is also done when vice versa happens.

A number object may be used instead of a primitive for the following reasons:
  • As an argument of a method that expects an object.
  • To use constants defined by a class.
  • To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems.


The Number class is an abstract class. It has some abstract methods, which can be inherited by the derived class and modified according to the requirement.

Formatting Numeric Print Output
The java.io package, provides format() and printf() methods in the PrintStream class, to format numeric output. These methods can be used like the regular printf() function in C/C++. The Syntax for both printf and format() is same.
public PrintStream format(String format, Object... args)
As in C, format specifiers are used, to enable formatting of the output. Format specifiers begin with a percent sign(%) and end with a converter. All converters, flags, and specifiers are documented in java.util.Formatter.
Example:
    int i = 38;
    System.out.format("The value of i is :%d%n", i);


%d denotes decimal integer
%n denotes newline character

The format() and printf() also have another argument called Locale. This is used to print the output in specific Locale. For example, Locale.FRANCE prints the output in French locale. In French locale, floating point numbers are printed with commas instead of decimals

Check out the sample TestFormat.java program in the tutorials page

DecimalFormat Class
The DecimalFormat is a subclass of NumberFormat Class, used to format decimal numbers. Using this, numbers can be parsed in different locales and patterns. The DecimalFormat class belongs to the java.text* package.

Check out the Demo program in the tutorials page.

MATH Class
The math class allows advanced arithmetic, beyond the operations performed by the arithmetic operators. The Math class includes more than 40 static methods. The key ingredients of this class:
  • Constants and Basic Methods
  • Exponential and Logarithmic Methods
  • Trignometric Methods
  • Random Numbers


tutorials

HTML Snippet: Lists

Consider the following Unordered List of BRIC Nations:

  • Brazil
  • Russia
  • India
  • China

In HTML, this is written as:
<UL>
<LI>Brazil
<LI>Russia
<LI>India
<LI>China
</UL>


For numbered-lists or ordered-lists just replace <UL>, </UL> tags with <OL>, </OL> respectively

Reference Links:
Lists in HTML

Basics: Inheritance

The Object is the first class in the JAVA Platform hierarchy. The object class does not have any parent class. All classes directly or indirectly inherit the object class. A class that has no parent class extends object class implicitly.

A subclass inherits all of the public and protected members of its parent. The inherited members can be used in the following ways:
  • The inherited fields can be used directly, just like any other fields.
  • You can declare a field in the subclass with the same name as the one in the superclass, thus hiding it
  • The inherited methods can be used directly as they are.
  • You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it.
  • You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it.
  • You can write a subclass constructor that invokes the constructor of the superclass, wither implicitly or by using the keyword super
A subclass can access the private fields of a superclass by using the public or protected methods of the superclass, if specified. A pubic or protected nested class can be inherited and used by a subclass, to access the private members of the superclass

Casting of Objects
A parent class object can be assigned with a derived class object. This is called implicit casting
Example:
    Object obj = new Rectangle();

If a derived class is assigned with a parent class, a compile-time error should occur. To avoid this, explicit casting is used.
Example:
    Rectangle rectOne = (Rectangle)obj;

Overriding Methods
When overriding a superclass method in the subclass, the @Override annotation can be used, to instruct the compiler that you want to override the method in the subclass. The access specifier for an overriding subclass method should allow more access, than the overriden superclass method. That is, a protected instance method in the superclass can only be made public but not private, in the subclass.

'super' Keyword
A superclass field is hidden by a subclass field of same name, even if their types are different. To access the superclass field, super keyword is used. Similarly, overriden methods in the superclass, can be invoked from the subclass using the keyword super. Constructor Chaining is a concept in which, a subclass constructor invokes a superclass constructor, either implicitly or explicitly and the chain goes all the way back to the object class constructor.
Examples:
    super.superClassMethod();
    super.superClassField = someVariable;
    super( parameter list ); - constructor of superclass

Methods in Object class
Any classes inherit object class methods. See Object class API specification to check the list of methods. The methods should be overriden according to the requirement in the derived class.
  • protected Object clone() throws CloneNotSupportedException
    Creates and returns a copy of this object. clone() can be invoked in a class that implements Cloneable interface. Else, the method throws a CloneNotSupportedException. Without any exceptions, the clone() method creates the object of the same class as the original object and initializes the new object's member variables to have the same values as the original object's corresponding member variables.
  • public boolean equals(Object obj)
    Compares two objects for equality and returns true if they are equal. Generally, identity operator (==) is used to determine equality for objects of primitive datatypes. For objects of reference datatypes, the equals() method, checks if the object references are equal or not.
  • protected void finalize() throws Throwable
    To free-up resources, when an object becomes garbage.
  • public final class getClass()
    Returns a Class object, which is used to get information, such as its name (getSimpleName()), its superclass(getSuperClass()), and the interfaces it implements(getInterfaces()). The getClass() method cannot be overriden.
  • public int hashCode()
    Returns a hash code value of the object, which is the objects memory address in hexadecimal. By definition, when 2 objects are equal, their hash code must also be equal.
Final Classes and Methods
A method can be defined as final to prevent it from being overriden in the subclass. A whole class can be declared as final, thus preventing it from being subclassed. String is an example of final class.

Abstract Classes and Methods
An Abstract class is a class that is declared abstract and it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can only subclassed.
Syntax:
    abstract ClassName{ Class Definition }

An abstract method is a method, declared without an implementation and ends with a semicolon.
Syntax:
    abstract returntype methodName(parameters);

All the methods in an interface are implicitly abstract.

Unlike interfaces, abstract classes can contain fields that are not static and final and also methods that have definition. An interface is an abstract class that contains only abstract method declarations. Unlike other classes, abstract classes can implement an interface without implementing all the interface's methods.

tutorials

StringBuilder class

StringBuilder is generally used as a peferrable replacement for the StringBuffer class. StringBuilder is used to construct a String from other datatypes. The principal operations are append() and insert() methods, which are overloaded to accept anytype of methods. Each method effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The final string is obtained by calling the toString() method.

StringBuilder has 4 types of constructors:
1. StringBuilder()
2. StringBuilder(CharSequence seq) - initialized with seq sequence
3. StringBuilder(int capacity) - constructs a string builder with an initial capacity
4. StringBuilder(String str) - initialized with String str

StringBuilder can perform operations such as reversing, replacing and finding the length of string.


JAVA API
tutorials

Java API Specification

The API Specification for JAVA Platform, Standard Edition 6 consists of clear descriptions for all classes and packages. There are 3793 classes and 203 packages in the sixth edition. Each class is explained with a clear description about it and summaries on the methods and fields used. On the other hand interfaces have only descriptions and method summaries. Class hierarchies, are shown for each and every class and interface. The tree display, will show the class hierarchy for all the 3793 classes. You can also view the classes, interfaces, annotations, exceptions, packages etc that have been deprecated in this edition. The specification does not oonsists of direct examples.

The API specification gives more than a detailed understand of each and every class, so click here, to view the API specification.

Monday, November 16, 2009

Basics: Interfaces

An interface is similar to a class, that contains only constants(defined with 'FINAL' keyword), method signatures, and nested types. Methods inside the interface do not have method body. Interfaces can only be implemented by another class or extended by other interfaces, but cannot be instantiated by class objects.

In JAVA, ,multiple inheritance is implemented through interfaces only. That is, a class can extend only one superclass whereas it can implement more than one interface. An interface can extend more than one interface.

Interface Body
o All methods declared in an interface are implicitly public
o All constant values defined in an interface are implicitly pubic,static and final.

When a new interface is defined, it means that a new reference data type is created. This new datatype can be used anywhere when required. A variable defined with this datatype, can be assigned with any object that is an instance of a class that implements the interface. This is done by casting of objects.
Syntax:
    Classname classObject = (Classname)interfaceObject;

Note:
A class that implements an interface must implement all the methods declared in the interface. Hence, care should be taken, so that all the required methods are declared in the interface. Any new methods, required by the interface, should be declared in a new interface which should extend the old interface.

Empty Interfaces, that contain zero methods, can also be used to mark classes. java.lang.Serializable is an example of empty interface.

tutorials

HTML Snippet: Symbols and Blank Spaces

  is used for a single blank space

If more identation is required on the left side, then
<span style="padding-left:20px">This line starts after some blank space at left</span>

&lt is used to display '<' symbol.

&gt is used to display '>' symbol

&amp is used to display '&' symbol

Reference Links
Spaces in HTML
Symbols in HTML

Basics: Class, Field, Method, Objects summarized

o A class can extend only one parent but can implement many interfaces

o The method signature comprises of two components -- the method's name and the parameters

o If a class is not provided with any constructors explicity, then the compiler automatically provides a no-argument, default constructor. This default constructor will call the no-argument constructor of the superclass. The compiler will complain in the case where a superclass is absent. If an explicit superclass does not exist, then the Object class will be the superclass implicitly.

o Varargs is used to pass an arbitrary number of values to a method. It is used when the number of arguments passed to a method of a particular datatype is unknown.

o To use Varargs, you follow the type of the last parameter by an ellipsis(3 dots ...), then a space, and the parameter name.

o Reference datatype parameters, such as objects, are also passed into methods by value. When the called-method returns, the passed reference still references the object as before calling the method. However, the values of the object's fields can be changed in the called method, if they have the proper access priviledges.

o A method returns to the code that invoked it, in 3 different occasions
   -completes all statements in the method
   -when the return keyword is encountered
   -throws an exception

o When a class name is used as a return type in a method declaration, the class of the type of returned object must be either a subclass of, or the exact class of, the return type.

Basics: Literals, arraycopy(), Statements

Literals
A literal is a source code representation of a fixed value; literals are represented directly in the code without requiring computation. In general, its possible to assign a literal to any primitive type variable as shown below:

boolean answer = false;
char initial = 'D';
String[] name = "Jackson";

Literals assigned to 'integer' type variables can be expressed using decimal, octal, or hexadecimal number systems. Either of the 3 systems will give the same value. 'Char' and 'String' type literals may contain unicode characters. If unicode is not supported by the system, then with the help of "Unicode Escape" i.e "\u" suffixed with the appropriate code will display the corresponding unicode character.

"S\u00ED" is "Si"

Char literals are always used with single quotes while String literals are used with double quotes.

Copying Arrays
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object sourceArray,
int startingPoint,
Object targetArray,
int targetStartingPoint,
int lenght)

The values in sourceArray, beginning from startingPoint upto the length specified are copied into the targetArray from the targetStartingPoint of the targetArray

Sample statement for arraycopy() method:
"System.arraycopy( copyFrom, 2, copyTo, 0, 7 );"


Classification of Statements
A statement is a single unit of execution. Statements can be classified into 3 types with each having subtypes:
1. Expression Statements
    o assignment statements
    o increment statements
    o method invocation statement
    o object creation statement
2. Declaration Statements
3. Control Flow Statements
    o decision-making statements
    o looping statements
    o branching

Branching Statements
'continue' and 'break' are the two branching statements. Each of them has 2 forms 'labeled' and 'unlabeled'. The unlabeled statements are used only to terminate or skip the innerblocks while the labeled statement blocks are used to terminate or skip the outerblocks.

The Syntax for labeled break and continue statements is:
label:
    OuterBlock
      InnerBlock
        break or continue;

Thursday, November 12, 2009

Briefing the Basics

Experience in Object Oriented Programming(OOPs) languages namely, C++, adds a bonus for learning JAVA. Although, I had prior exposure to JAVA, the importance of going through the basics is not a lesser one. Hence, I thought of quickly going through the fundamentals of JAVA programming, to prepare myself for furthur concepts which will be based on the fundamentals.

The Getting Started section of JAVA Tutorials, is a clear introduction of what is JAVA? For beginners, you can find the HelloWorld program, along with the procedure to execute the program on different platforms(Solaris, Windows, Linux). So try it out.

Objects, Classes, Interfaces and Packages are the primary entities of Object Oriented Programming
Variables, Operators, Expressions, Statements and Control Flow are the common features of programming

Tuesday, November 10, 2009

Sun's Java Tutorials

The Java Tutorials was the first page that I had opened through my sun's online account. The page was nicely setup and explains all the core features of JAVA in a practical fashion. It starts from basic learning about JAVA features to designing GUI's and finally all the special implementations of JAVA for networking, internet applications, graphics etc.

On having a prior experience with JAVA, I directly went to Swing Programming, which is about designing GUI's. The first Swing program that I wrote was to display "Hello World" in a graphic window. When I tried to compile the program with javac command, my first error cropped up. The error occurred because of PATH setting which had to be updated once JDK is installed. Once the setting was put in place the program ran successfully.
Follow the JDK Installation Instructions to know more on path setting.

My next tutorial was to create a Celsius to Fahrenheit temperature converter using Netbeans IDE. It was my first experience to designing a GUI using Netbeans, without doing much hardcoding.

tutorials:
HelloWorld Application
Temperature Converter

related links
The JFC/Swing Tutorial

My Sun Connection

My Sun Connection, is a onestop online relationship with SUN. Its a gateway to all information about Sun's activities and products. Once signed in, the account opens into a multi-tabbed page which can be customized to ones own preferences. The page is similar to iGoogle page where you can have lot of widgets updating you with different information. In my sun connection, you have widgets on several topics pertaining to sun.

Registeration is a simple process and once your account is created you can access all the products and information.

Netbeans & JDK

Installed Netbeans IDE 6.7.1 along with JDK 6 on Windows Vista SP2 the previous day. The download page for the installation file included 3 types of JDK files. The one which included Netbeans was downloaded. Using this single file both Netbeans and JDK can be installed concurrently.

Installing the softwares was a simple process. Once completed, Netbeans had to be updated with 2 new updates.

Hence the setup was ready for me, to start my Kinder Garden in JAVA. As a reference, I am using JAVA How to Program, Sixth Edition, Deital Deital. The book is written for any kind of user (beginner,intermediate or expert). Though its best for beginners, it is a good reference book for intermediates like me as well. Currently the seventh edition is available for sale in stores. The latest edition is written with JDK 6 as the platform. Click here, to buy one for yourself.