Friday, January 30, 2009

JAVA ENUM Key Notes for SCJP

Enumerations are set of closely related items, often called Type Safe Enum that are introduced in JDK 5. It is the better way to define constants, but it is more than that. you can read and test the examples from online sun tutorials on enums.

Couple of Key notes that I have noted are as followings:

  1. enums are implicitly final subclasses of java.lang.Enum that is inherited from java.lang.Object.
  2. As enums are implicitly final classes, so inheritance between enums or simple classes is not possible.
  3. If an enum is member of a class it is implicitly static.
  4. new keyword can never be used with enum.
  5. name() and valueOf() methods simply use the text of enum constant.
  6. Defualt implementation of toString() returns the name of the enum constant, but you can override its implementation.
  7. For enum constants equals() and == amount to the same thing and can be used interchangebly.
  8. enum constants are implicitly public, static and final
  9. The order of appearance of enum constants is called their NATURAL ORDER
  10. There is a built in method named as values() that returns the array of all enum constants.
  11. All instances of Enums are serializable by default. As Enums are subclasses of class java.lang.Enum, which implements the interface java.io.Serializable. If a class implements the interface java.io.Serialisable, its objects are serializable.
  12. Enums are compiled to a .class file.
  13. An enum can define a main method and it can be executed as a standalone application
  14. You can provide the abstract methods in the enum, but this abstract method needs to be implemented by all of the enum constants because we can not declare enum itself as abstract. Simply We cannot define abstract enums.
  15. Enums cannot be instantiated, we can only create the reference of an enum
  16. Enums may be used as a operand for the instanceof operator in the same way that it can be used by a class
  17. Enums can be used in switch statements.
  18. An enum can define more than 1 constructor (similar to a class) and its constructor can accept more than 1 method parameter. Please note we can not create the actual object using new like we do with classes.
  19. name() is a final method, which cannot be overridden. It returns the name of the enum constant, exactly as declared in its enum declaration.
  20. Constructors for an enum type should be declared as private. The compiler allows non
    private declares for constructors, but this seems misleading to the reader, since new can
    never be used with enum types.
  21. Constructor of enum can only be private or default. public and protected are not allowed with constructor of Enum.
  22. Enum can implement interface.
  23. Enums cannot be declared within a method!

Monday, January 19, 2009

UET Lahore among the top world ranking universities (2008)

The University of Engineering and Technology, Lahore has been placed at 592 among the top ranked Universities of the world in World Ranking Universities 2008.
It is a remarkable achievement for UET, Lahore that it has got international recognition.
It is also worth noting that only Four Pakistani Universities including UET, Lahore are included in the World Ranking 2008.

http://www.topuniversities.com/university_rankings/results/2008/overall_rankings/fullrankings/

Wednesday, January 14, 2009

JAVA: Named Inner-class Listeners

Defining an inner class listener to handle events is a very popular style.

  1. Access:-Use an inner class rather than an outer class to access instance variables of the enclosing class. In the example below, the txt1, txt2, txt3 can be referenced by the listener class. Because simple program listeners typically get or set values of other widgets in the interface, it is very convenient to use an inner class.
  2. Reuse:-Unlike anonymous inner class listeners, it's easy to reuse the same listener for more than one control, eg, the click of a button might perform the same action as the equivalent menu item, and might be the same as hitting the enter key in a text field.
  3. Organization:- It's easier to group all the listeners together with inner classes than with anonymous inner class listeners.

EXAMPLE No:1 Using One Inner class for different Events

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

/***
*
* @author Sabah u Din Irfan
* @Description ActionListener Example Using Named Inner Classes
*
***/
public class ActionListenerInnerClassDemo extends JFrame{

JLabel lbl ;
JTextField txt1;
JTextField txt2;
JTextField txt3;
JButton btnAdd;
JButton btnSub;

ActionListenerInnerClassDemo()
{
// Set Frame Window properties
super("Action Listner Demo!!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Get Container
Container container = getContentPane();
container.setLayout(new FlowLayout());
// Create Components
lbl = new JLabel(" Please Enter two values in text fields:");
txt1 = new JTextField(15);
txt2 = new JTextField(15);
txt3 = new JTextField(15);
btnAdd = new JButton("Add");
btnSub = new JButton("Sub");
// Add Components

container.add(lbl);
container.add(txt1);
container.add(txt2);
container.add(txt3);
container.add(btnAdd);
container.add(btnSub);

// Add Action Listners.. Use Annonymous Inner Classes
MyListener listener = new MyListener();

btnAdd.addActionListener(listener);
btnSub.addActionListener(listener);

// Make frame visible and set its size
setVisible(true);
pack();
} // end of Constructor

// Private Named Inner Class to Handle the Events
//////////////////////////////////////////////////////
private class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
if ( e.getSource() == btnAdd)
{
int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a+b;

txt3.setText(c+"");
}
else if( e.getSource() == btnSub)
{
int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a-b;

txt3.setText(c+"");
}

}
}// end named inner class MyListener
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ActionListenerInnerClassDemoframe = new ActionListenerInnerClassDemo();

}

}

EXAMPLE No:2 Using Different Inner classes for different Events


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

/***
*
* @author Sabah u Din Irfan
* @Description ActionListener Example Using Named Inner Classes
*
***/
public class ActionListenerInnerClassDemo extends JFrame{

JLabel lbl ;
JTextField txt1;
JTextField txt2;
JTextField txt3;
JButton btnAdd;
JButton btnSub;

ActionListenerInnerClassDemo()
{
// Set Frame Window properties
super("Action Listner Demo!!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Get Container
Container container = getContentPane();
container.setLayout(new FlowLayout());
// Create Components
lbl = new JLabel(" Please Enter two values in text fields:");
txt1 = new JTextField(15);
txt2 = new JTextField(15);
txt3 = new JTextField(15);
btnAdd = new JButton("Add");
btnSub = new JButton("Sub");
// Add Components

container.add(lbl);
container.add(txt1);
container.add(txt2);
container.add(txt3);
container.add(btnAdd);
container.add(btnSub);

// Add Action Listners.. Use Annonymous Inner Classes
AddListener addlistener = new AddListener();
SubListener sublistener = new SubListener();

btnAdd.addActionListener(addlistener);
btnSub.addActionListener(sublistener);

// Make frame visible and set its size
setVisible(true);
pack();
} // end of Constructor

// Private Named Inner Classes to Handle the Events
//////////////////////////////////////////////////////
private class AddListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {

int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a+b;

txt3.setText(c+"");
}
}// end named inner class
private class SubListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {

int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a - b;

txt3.setText(c+"");
}
}// end named inner class MyListener
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ActionListenerInnerClassDemo frame = new ActionListenerInnerClassDemo();

}

}

JAVA: Anonymous Listeners

There is no need to define a named class simply to add a listener object to a button. Java has a somewhat obscure syntax for creating an anonymous innner class listener that implements an interface. There is no need to memorize the syntax; just copy and paste it each time. For example,
class myPanel extends JPanel {
. . .
public MyPanel() {
. . . //in the constructor
JButton b1 = new JButton("Hello");
b1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something for button b1
}
}

);

Creates a class

The above example creates a subclass of Object that implements the ActionListener interface. The compiler creates names for anonymous classes. The JDK typically uses the enclosing class name followed by $ followed by a number, eg, you may see a MyPanel$1.class file generated by the compiler.


ActionListener Example Using Anonymous Inner Classes
-------------------------------------------------------------



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

/****
*
* @author Sabah u Din Irfan
* @Description ActionListener Example Using Anonymous Inner Classes
*/
public class ActionListnerDemo extends JFrame{

JLabel lbl ;
JTextField txt1;
JTextField txt2;
JTextField txt3;
JButton btnAdd;
JButton btnSub;

ActionListnerDemo()
{
// Set Frame Window properties
super("Action Listner Demo!!");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Get Container
Container container = getContentPane();
container.setLayout(new FlowLayout());
// Create Components
lbl = new JLabel(" Please Enter two values in text fields:");
txt1 = new JTextField(15);
txt2 = new JTextField(15);
txt3 = new JTextField(15);
btnAdd = new JButton("Add");
btnSub = new JButton("Sub");
// Add Components

container.add(lbl);
container.add(txt1);
container.add(txt2);
container.add(txt3);
container.add(btnAdd);
container.add(btnSub);

// Add Action Listners.. Use Annonymous Inner Classes

btnAdd.addActionListener( new ActionListener() {

public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a+b;

txt3.setText(c+"");

}
}
);

////////////////////
btnSub.addActionListener( new ActionListener() {

public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(txt1.getText());
int b = Integer.parseInt(txt2.getText());

int c = a-b;

txt3.setText(c+"");

}
}
);

// Make frame visible and set its size
setVisible(true);
pack();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ActionListnerDemo frame = new ActionListnerDemo();

}

}

Saturday, January 10, 2009

Javascript: Function To Check Whether TextField is ReadOnly

The following Javascript function can be used to check whether the given control is read only or not?

Sample 1:

function isReadOnly()
{

var m = document.getElementById("TextBox1").getAttribute("Readonly");
if (m==true)
{
alert('Read Only!');
return true;
}

else

{

alert('Not Read Only');

return false;

}


}

Sample 2:


function isReadOnly(controlID)
{

var m = document.getElementById(
controlID).getAttribute("Readonly");

if (m==true)
{
alert('Read Only!');

return true;

}

else

{

alert('Not Read Only');

return false;

}


}

Friday, January 9, 2009

JavaScript: Masking on Text Field

It is quite often that when we create HTML forms we need masking in fields and most of the times in text fields(Text Boxes) for some specific type of input like for DATE, PHONE NO, CURRENCY etc. Couple of server side technologies provide built in controls for most common masking but a few does not.

The following Javascript function provides you the facility to customize you text boxes with specific masking.

For Example, you may need masking for data input like : DD/MM/YYYY e.g 31/12/2008
Similarly sometimes you may want to provide masking like: 121-23-1231
and sometimes you may want to provide masking like: 12-42-1412

The following function is smart enough to handle all these requirements with a little change in the input parameter.

function mask(str,textbox,loc,delim){
var locs = loc.split(',');

for (var i = 0; i <= locs.length; i++){
for (var k = 0; k <= str.length; k++){
if (k == locs[i]){
if (str.substring(k, k+1) != delim){
str = str.substring(0,k) + delim + str.substring(k,str.length)
}
}
}
}
textbox.value = str
}

Where the parameters are for:
  1. str - the value of the current textbox control,
  2. textbox - the actual textbox object, (so that the value can be set)
  3. loc - a string of multiple locations to place the specified character,
  4. delim - the character (delimiter) that you want to use a separator.
Examples to Call this function:

Step 1:
First of all add this function in the head section.

Step 2:
You need to call this function on onKeyUp & onBlur events like:

To provide the output like(121-23-1231):

You need to call this javascript function like:
< name="Field1" value="" type="text" onkeyup="javascript:return mask(this.value,this,'3,6','-');" onblur="javascript:return mask(this.value,this,'3,6','-');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="11">



To provide the output like(21/12/2009):

You need to call this javascript function like:
< name="Field2" value="" type="text" onkeyup="javascript:return mask(this.value,this,'2,5','/');" onblur="javascript:return mask(this.value,this,'2,5','/');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">


To provide the output like(12,23,2312):

You need to call this javascript function like:
< name="Field3" value="" type="text" onkeyup="javascript:return mask(this.value,this,'2,5',',');" onblur="javascript:return mask(this.value,this,'2,5',',');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">

To provide the output like(12#32#1312):

You need to call this javascript function like:
< name="Field3" value="12#32#1312" type="text" onkeyup="javascript:return mask(this.value,this,'2,5','#');" onblur="javascript:return mask(this.value,this,'2,5','#');" style="font-family:verdana;font-size:10pt;width:110px;" maxlength="10">

You may change your mask symbol and the places accordingly using the provided parameters.

Thursday, January 8, 2009

Javascript: Function To Validate Date Format DD/MM/YYYY

Please use the following java script to validate the Date in the format(DD/MM/YYYY) wherever you needed in transcription screens:

Place this code in the head section of your HTML/JSP and pass the value(12/12/2008) to function named as validateDateDDMMYYY(‘12/12/2008’)


function validateDateDDMMYYY(DateOfBirth)
{

var Char1 = DateOfBirth.charAt(2);
var Char2 = DateOfBirth.charAt(5);
// alert(Char1); alert(Char2);

var flag =false;

if ( Char1 =='/' && Char2 == '/' )
{
// alert ('valid positions of non numeric characters.');
flag = true;
}
else
{
// alert('invalid position of non numeric symbols');
flag =false;
}

var day;
var month;
var year;

day = DateOfBirth.substring(0,2);
month = DateOfBirth.substring(3,5);
year = DateOfBirth.substring(6,10);

// alert(day); alert(month);alert(year);
if( validDay(day) && validMonth(month) && validYear(year) && (flag ==true) )
{
// alert(' Valid Date')
return true;
}
else
{
alert('Invalid Date Format: Please enter DD/MM/YYYY for Date of Birth!');
return false;
}

} // end func

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;

for (i = 0; i < sText.length && IsNumber == true; i++)
{
Char = sText.charAt(i);
if (ValidChars.indexOf(Char) == -1)
{
IsNumber = false;
}
}

return IsNumber;
} // end func


function validDay(day)
{
if ( IsNumeric(day) )
{
if( day >0 && day <32)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}

}// end func


function validMonth(month)
{
if ( IsNumeric(month) )
{
if( month >0 && month <13)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}// end func



function validYear(year)
{
var d = new Date();
var currentYear = d.getFullYear();

if( year.length!= 4) { return false; }

if ( IsNumeric(year) )
{
if( year >0 && year <=currentYear)
{
return true;
}
else
{
return false;
}

}
else
{
return false;
}

}// end func

Javascript: Function To Validate Date Format DD/MM/YYYY

unhidewhenused="false" name="Medium Grid 2 Accent 1">

Pleas



function validateDateDDMMYYY(DateOfBirth)
{

var Char1 = DateOfBirth.charAt(2);
var Char2 = DateOfBirth.charAt(5);
// alert(Char1); alert(Char2);

var flag =false;

if ( Char1 =='/' && Char2 == '/' )
{
// alert ('valid positions of non numeric characters.');
flag = true;
}
else
{
// alert('invalid position of non numeric symbols');
flag =false;
}

var day;
var month;
var year;

day = DateOfBirth.substring(0,2);
month = DateOfBirth.substring(3,5);
year = DateOfBirth.substring(6,10);

// alert(day); alert(month);alert(year);
if( validDay(day) && validMonth(month) && validYear(year) && (flag ==true) )
{
// alert(' Valid Date')
return true;
}
else
{
alert('Invalid Date Format: Please enter DD/MM/YYYY for Date of Birth!');
return false;
}

} // end func

function IsNumeric(sText)
{
var ValidChars = "0123456789.";
var IsNumber=true;
var Char;

for (i = 0; i < sText.length && IsNumber == true; i++) { Char = sText.charAt(i); if (ValidChars.indexOf(Char) == -1) { IsNumber = false; } } return IsNumber; } // end func function validDay(day) { if ( IsNumeric(day) ) { if( day >0 && day <32) { return true; } else { return false; } } else { return false; } }// end func function validMonth(month) { if ( IsNumeric(month) ) { if( month >0 && month <13) { return true; } else { return false; } } else { return false; } }// end func function validYear(year) { var d = new Date(); var currentYear = d.getFullYear(); if( year.length!= 4) { return false; } if ( IsNumeric(year) ) { if( year >0 && year <=currentYear)
{
return true;
}
else
{
return false;
}

}
else
{
return false;
}

}// end func


Saturday, January 3, 2009

SQL Server: WAITFOR TIME Statement

WAITFOR TIME SQL statement is used to set the particular time to execute the next query/SQL statement.

For Example the second query will execute when the particular time will be reached:

DECLARE @MyDateTime DATETIME
/* Add 5 seconds to current time so
system waits for 15 seconds*/
SET @MyDateTime = DATEADD(s,15,GETDATE())
SELECT GETDATE() CurrentTime
WAITFOR TIME @MyDateTime
SELECT GETDATE() CurrentTime

SQL Server: WAITFOR DELAY Statement to set Delay in Queries

WAITFOR DELAY statement is used in T-SQL to set the delay time between the SQL queries. For example the second query will execute after 10 seconds of delay:

SELECT GETDATE() CurrentTime
WAITFOR DELAY ‘00:00:10′ —- 10 Second Delay
SELECT GETDATE() CurrentTime