BidVertiser

Wednesday, December 31, 2008

Inner classes in JAVA

The Java programming language allows you to define a class within another class. Such a class is called a nested class.

Inner classes nest within other classes. A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:

  • Static member classes
  • Member classes
  • Local classes
  • Anonymous classes

static member class is a static member of a class. Like any other static method, a static member class has access to all static methods of the parent, or top-level, class.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass 
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Like a static member class, a member class is also defined as a member of a class. Unlike the static variety, the member class is instance specific and has access to any and all methods and members, even the parent's this reference.

Local classes are declared within a block of code and are visible only within that block, just as any other method variable.

 an anonymous class is a local class that has no name.

Why Use Nested Classes?

There are several compelling reasons for using nested classes, among them:
  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.


Monday, December 22, 2008

JAVA and Internet

Hi All...
in this age of Internet, java and Internet are very closely related.java made web interactive. now a days lot of web applications are made in java/j2ee.java is very much secure that's the main reason behind the usage of java in web.J2EE provides lot of APIs to make highly secure enterprise application.

Sunday, December 21, 2008

Garbage Collection in java

One of the ideas behind Java's automatic memory management model is that programmers be spared the burden of having to perform manual memory management. In some languages like C,C++, the programmer allocates memory for the creation of objects stored on the heap and the responsibility of later deallocating that memory also resides with the programmer. If the programmer forgets to deallocate memory or writes code that fails to do so, a memory leak occurs and the program can consume an arbitrarily large amount of memory. Additionally, if the program attempts to deallocate the region of memory more than once, the result is undefined and the program may become unstable and may crash. Finally, in non garbage collected environments, there is a certain degree of overhead and complexity of user-code to track and finalize allocations. Often developers may box themselves into certain designs to provide reasonable assurances that memory leaks will not occur.

In Java, this potential problem is avoided by automatic garbage collection. The programmer determines when objects are created, and the Java runtime is responsible for managing the object's lifecycle. The program or other objects can reference an object by holding a reference to it (which, from a low-level point of view, is its address on the heap). When no references to an object remain, the Java garbage collector automatically deletes the unreachable object, freeing memory and preventing a memory leak. Memory leaks may still occur if a programmer's code holds a reference to an object that is no longer needed—in other words, they can still occur but at higher conceptual levels.

The use of garbage collection in a language can also affect programming paradigms. If, for example, the developer assumes that the cost of memory allocation/recollection is low, they may choose to more freely construct objects instead of pre-initializing, holding and reusing them. With the small cost of potential performance penalties (inner-loop construction of large/complex objects), this facilitates thread-isolation (no need to synchronize as different threads work on different object instances) and data-hiding. The use of transient immutable value-objects minimizes side-effect programming.

Tuesday, December 2, 2008

Java Database connectivity and it's Drivers

Why should you consider Java Database Connectivity (JDBC) drivers apart from the JDBC-ODBC Bridge? What level of JDBC driver is suited for your application? What parameters should you use for evaluating a JDBC driver? This article evaluates various JDBC drivers and answers these questions.

While writing JDBC applications, developers generally start with JDBC-ODBCBridge to connect to databases. But when an application reaches some advanced stage, for example, when it needs to support multithreading, the JDBC-ODBCBridge poses a few problems. So, the need arises for a robust JDBC driver. In that case, the type of driver depends on quite a few parameters: whether the application is Internet or intranet based, whether it needs to support heterogeneous databases, the number of concurrent users, and so on.

JDBC driver types

JDBC drivers are divided into four types or levels. Each type defines a JDBC driver implementation with increasingly higher levels of platform independence, performance, and deployment administration. The four types are:


Type 1: JDBC-ODBC Bridge
Type 2: Native-API/partly Java driver
Type 3: Net-protocol/all-Java driver
Type 4: Native-protocol/all-Java driver
Type 1: JDBC-ODBC Bridge
The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many cases, the client database code, must be present on the client machine.

Pros
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available. Type 1 drivers may be useful for those companies that have an ODBC driver already installed on client machines.

Cons

The performance is degraded since the JDBC call goes through the bridge to the ODBC driver, then to the native database connectivity interface. The result comes back through the reverse process. Considering the performance issue, type 1 drivers may not be suitable for large-scale applications.

The ODBC driver and native connectivity interface must already be installed on the client machine. Thus any advantage of using Java applets in an intranet environment is lost, since the deployment problems of traditional applications remain.
Type 2: Native-API/partly Java driver
JDBC driver type 2 -- the native-API/partly Java driver -- converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine.

Pros
Type 2 drivers typically offer significantly better performance than the JDBC-ODBC Bridge.

Cons
The vendor database library needs to be loaded on each client machine. Consequently, type 2 drivers cannot be used for the Internet. Type 2 drivers show lower performance than type 3 and type 4 drivers.

Type 3: Net-protocol/all-Java driver
JDBC driver type 3 -- the net-protocol/all-Java driver -- follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.

Pros
The net-protocol/all-Java driver is server-based, so there is no need for any vendor database library to be present on client machines. Further, there are many opportunities to optimize portability, performance, and scalability. Moreover, the net protocol can be designed to make the client JDBC driver very small and fast to load. Additionally, a type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing.

Cons
Type 3 drivers require database-specific coding to be done in the middle tier. Additionally, traversing the recordset may take longer, since the data comes through the backend server.

Type 4: Native-protocol/all-Java driver
The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues.

Pros
Since type 4 JDBC drivers don't have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. Moreover, the native-protocol/all-Java driver boasts better performance than types 1 and 2. Also, there's no need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Cons
With type 4 drivers, the user needs a different driver for each database.

Performance evaluation of five specific JDBC drivers
To evaluate the performance of five industry-standard drivers based on parameters such as average connection time, data retrieval time, and record insertion time, I created a sample database in SQL Server 7.0. I picked industry-standard JDBC drivers representing various driver types. Note: I didn't test any type 2 drivers because they are not readily available in the market, and I wanted to stick with pure-Java drivers for this article.

Basic Point to rember in Corejava

1. when start writing Source file’s elements (in order)
a. Package declaration
b. Import statements
c. Class/Interface definitions
2. Importing packages doesn’t recursively import sub-packages.
3. Java language automatically imports all classes and interfaces in the java.lang package.
The compiler treats each source file as if its first import statement were
import java.lang.*; // implicit in every Java source file
4. Sub-packages are really different packages, happen to live within an enclosing package. Classes in sub-packages cannot access classes in enclosing package with default access.
5. There can be an ambiguous situation if two packages happen to have classes with the same name and you don’t explicitly provide a fully qualified name.
import java.sql.*;
import java.util.*;
…..
System.out.println(new Date()); //ERROR
System.out.println(new java.util.Date()); //OK
…..
6. Comments can appear anywhere. Can’t be nested.(No matter what type of comments). There are three types of comments in Java.
(a) Single Line //
(b) Multi Line /* …. */
(c) Documentation Comment /** ……. **/
· If // appears, everything will be commented out after it, in the same line
· If /* or /** appears, it will comment all the content till the first encoutered */
Examples
/* This is a comment */ [OK]
/** This is a comment */*/ [ERROR]
// /* This is a comment */ */ [OK]
/* // This is a comment */ [OK]
7. At most one public class definition per file. This class name should match the file name. If there are more than one public class definitions, compiler will accept the class with the file’s name and give an error at the line where the other class is defined.
8. Even an empty file is a valid source file. It can be compiled but can’t run.
9. An identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.
10. An identifier cannot have a name of a Java keyword. Embedded keywords are OK. true, false and null are literals (not keywords), but they can’t be used as identifiers as well.
11. const and goto are reserved words, and can’t be used as identifiers. You must differentiate between keywords, reserved words and literals.
12. Unicode characters can appear anywhere in the source code. The following code is valid.
ch\u0061r a = 'a';
char \u0062 = 'b';
char c = '\u0063';
12. Java has 8 primitive data types.
boolean
byte
short
char
int
long
float
Double
13. All numeric data types are signed. char is the only unsigned integral type.
14. Object reference variables are initialized to null.
public class TestProgram{
static String s1;
static String s2;
public static void main(String args[]){
s2=s1+s2;
System.out.println(s2);
System.out.println(s1);
}
}
Output : nullnull
null
15. Octal literals begin with zero. Hex literals begin with 0X or 0x.
16. Char literals are single quoted characters or unicode values (begin with \u).
17. A number is by default an int literal, a decimal number is by default a double literal.
18. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that it’s an identifier)
19. Two types of variables.
Member variables
· Accessible anywhere in the class.
· Automatically initialized before invoking any constructor.
· Static variables are initialized at class load time.
· Can have the same name as the class.
Automatic variables (method local)
· Must be initialized explicitly. (Or, compiler will catch it.) Object references can be initialized to null to make the compiler happy. Local variables can’t have any accessibility modifier, also can’t be marked static, volatile, transient, but can be final. The following code won’t compile. Specify else part or initialize the local variable explicitly.

public String testMethod ( int a) {
String tmp;
if ( a > 0 ) tmp = “Positive”;
return tmp;
}
· Can have the same name as a member variable, resolution is based on scope, in such a case “this” keyword is used.
Member Variables
Local Variables/Automatic Variables
Created when an instance is created and are destroyed when the object is destroyed (or garbage collected)

Thus, accessible anywhere within the class.
Created on entry to the method or initialization block, exists only during the execution of the method or block

Accessible only inside the method where defined.
All member variables that are not explicitly assigned a vales upon declaration are automatically assigned initial value
Local variables are not implicitly assigned value. This can cause a compile time error if we try to access an un-initialized local variable.
.Can have any accessibility modifier (public, private, protected) and other modifiers like transient, final, static and volatile
Can’t have any accessibility modifier.

Can be final.

Member variables can further be classified in two categories – (1) Instance variables, and (2) static or class variables.
Note that array types whether member or local are implicitly initialized with default values when no explicit assignment has been made.

20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created. Since arrays are implemented as Objects in Java, Arrays in Java implicitly extend from the Object class. This means that you can call any method of the Object class from an Array reference.
int i[]=new int[2];
int j[]=new int[2];
System.out.println(i.equals(j)); //false
System.out.println(i.toString()); //prints hash code

21. Arrays should be
22. Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
23. Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
24. Initialized. for (int i = 0; i < a.length; a[i++] = 0)
25. The above three can be done in one step.
int a[] = { 1, 2, 3 }; (or )
int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.
23. Java arrays are static arrays. Size has to be specified at compile time. array_ref.length returns array’s size. (Use Vectors for dynamic purposes).
Since, Java arrays are dynamically created at run time, we can specify variable rather than a literal to specify the size of the array.
24. Array size is never specified with the reference variable, it is always maintained with the array object. It is maintained in array.length, which is a final instance variable.
25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]
Example
public class TestProgram {
static int[] method(){
return new int[]{34,90,12,89,10,90};
}
static int min(int arr[]){
int least=arr[0];
for(int i=1;i if(arr[i] least=arr[i];
return least;
}
public static void main(String args[]){
System.out.println("smallest element "+min(method()));
}
}
26. Arrays with zero elements can be created. args array to the main method will be a zero element array if no command parameters are specified. In this case args.length is 0. There is a strong bounds checking on Java Arrays, For example, if you try to access (e.g. System.out.println(args[0])), and if no command line arguments are provided then an ArrayIndexOutOfBoundsException will be thrown.
27. Comma after the last initializer in array declaration is ignored.

int[] i = new int[2] { 5, 10}; // Wrong
int i[5] = { 1, 2, 3, 4, 5}; // Wrong
int[] i[] = {{}, new int[] {} }; // Correct
int[] i[] = {null, new int[] {} }; // Correct
int i[][] = { {1,2}, new int[2] }; // Correct
int i[] = { 1, 2, 3, 4, } ; // Correct
· When constructing multidimensional arrays with the new operator, the length of the deeply nested array may be ignored.
int i[][]=new int[4][]; //OK
int i[][]=new int[][4]; //Wrong
int i[][]=new int[4][4]; //OK
Note,
int[] i[] = {null, new int[] {2,3} };
System.out.println(i[1]); //calls the toString() method, prints hash code
System.out.println(i[0]); //this will print null

for(int j=0;j {
for(int k=0;k System.out.println(i[j][k]);
}
Output: [I@df6ccd
null
Exception in thread "main" java.lang.NullPointerException

28. Array indexes start with 0. Index is an int data type.
29. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them.
Example :
int[] a,b; // here both a and b are arrays of type “int”
int a[],b; //only a ia an “int” array, b is an “int” variable
When the [] notation follows the type, all the variables in the declaration are arrays