Wednesday, December 10, 2008

make autorun cd

If you want to make a autorun file for that CD you are ready to burn

here is a small trick for u


1) You open notepad
2) now you writ: [autorun]
OPEN=INSTALL\aaa.EXE
ICON=INSTALL\aaa.EXE

Now save it but not as a .txt file but as a aaa.inf file.

But remember! And you also need to rember that it is not all of the setup files there are called '.exe but some are called '.msi

3) Now burn your CD with the autorun aaa.inf file included.

4) Now set the CD in you CD drive and wait for the autorun to begin or if nothing happens just double-click on the CD drive in "This Computer"

Tuesday, November 18, 2008

AJAX features

AJAX is a mixture of several popular technologies put together to build the next generation of web applications, which are more responsive, more interactive and behave like their desktop counterparts. MX AJAX Toolbox brings the benefits of AJAX to Dreamweaver.
Asynchronous loading of content without page refresh
With MX AJAX Toolbox, an AJAX site has one or more master pages. The building blocks of any master page are the AJAX panels – regions of content that users can place anywhere in their site and that change their state independently from the rest of the page. Each AJAX panel has one or more states – the actual files included in the website when an AJAX request that calls them is performed. AJAX Panels can be reused across multiple master pages, in order to reduce development time. For instance, you can reuse a menu panel in all your site pages, without having to rebuild it each time.




When AJAX links are clicked within a site, only the targeted panel state is loaded, independently and asynchronously, without refreshing the whole page.
Working with AJAX panels will appear very familiar to developers, since the approach is similar to using editable regions in Dreamweaver templates, or using master pages in Microsoft Visual Studio.
Increased interactivity and responsiveness
With MX AJAX Toolbox, developers can build Rich Internet Applications (RIA) that interact with site visitors, offering them a unique web experience. Visitors can continue using the website while parts of it load separately and asynchronously. They will enjoy the increased interactivity that comes with a suite of AJAX controls and widgets included in the toolbox. AJAX websites will render fast on their first load, while incrementally loading necessary JavaScript files in the background. This means users on slow connections (such as dial-up) will be able to see and interact with the website immediately after they access it.
Reduced loading time and server traffic
Since only parts of the site are loaded at one time (states of the AJAX panels), the loading time is obviously shorter than if the whole page refreshed. Server traffic is considerably reduced. Because only parts of the page content are sent, the bandwidth usage decreases and websites will appear to load seamlessly.

Monday, November 10, 2008

The Purpose of the Marker Interface

One of the "clean" features of the Java programming language is that it mandates a separation between interfaces (pure behavior) and classes (state and behavior). Interfaces are used in Java to specify the behavior of derived classes.

Often you will come across interfaces in Java that have no behavior. In other words, they are just empty interface definitions. These are known as marker interfaces. Some examples of marker interfaces in the Java API include:


- java,lang.Cloneable
- java,io.Serializable
- java.util.EventListener



Marker interfaces are also called "tag" interfaces since they tag all the derived classes into a category based on their purpose. For example, all classes that implement the Cloneable interface can be cloned (i.e., the clone() method can be called on them). The Java compiler checks to make sure that if the clone() method is called on a class and the class implements the Cloneable interface. For example, consider the following call to the clone() method on an object o:


SomeObject o = new SomeObject();
SomeObject ref = (SomeObject)(o.clone());


If the class SomeObject does not implement the interface Cloneable (and Cloneable is not implemented by any of the superclasses that SomeObject inherits from), the compiler will mark this line as an error. This is because the clone() method may only be called by objects of type "Cloneable." Hence, even though Cloneable is an empty interface, it serves an important purpose.

IO Operations - Reading a File

package com.test.corejava;

/**
*
* @author seetharam
*/
import java.io.*;

public class IOReading {

/**
* Fetch the entire contents of a text file, and return it in a String.
* This style of implementation does not throw Exceptions to the caller.
*
* @param aFile is a file which already exists and can be read.
*/
public static String getContents(File aFile) {
//...checks on aFile are elided
StringBuilder contents = new StringBuilder();

try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String strLine = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while (( strLine = input.readLine()) != null){
contents.append(strLine);
contents.append(System.getProperty("line.separator"));
}

}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}

return contents.toString();
}
public static void main(String a[]){

File f= new File("c:/myfile.txt");
String str =getContents(f);
System.out.println(str);
}
}

idempotent request and non-idempotent request - in HttpServletResquest Header

Official definition from dictionary.com is "unchanged when multiplied by itself". In HTTP perspective, you can send idempotent requests multiple times without altering system state / data / resource.

Since get requests are meant to get required resource and not change anything, it's considered idempotent. Although technically it's feasible to implement your program in bad way that would alter the data even for get request.

Post request are usually implemented to achieve server side action that would alter data. For example, providing your credit card and submitting purchase button. If you submit the button twice, chances are that you might pay twice! Since post requests are non-idempotent, one should take extra care in implementing it such that duplicate request doesn't go through.

mutable and immutable objects in java

As per the dictionary, mutable objects are objects which can change their values and immutable objects are objects which cannot have their values changed.

>>java.lang.String is an example of an immutable object in Java
whereas
>>java.lang.StringBuffer is a mutable object.

Sunday, November 9, 2008

response.sendRedirect-RequestDispatcher.forward-PageContext.forward

Q. What is the difference between response.sendRedirect(), RequestDispatcher.forward(), and PageContext.forward()?

In a nutshell, RequestDispatcher.forward() works on the server and response.sendRedirect() works on the browser. When you invoke RequestDispatcher.forward(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file. When you invoke response.sendRedirect(), this sends an HTTP response to the browser to make another request at a different URL.

RequestDispatcher.forward()
and PageContext.forward() are effectively the same. PageContext.forward() is a helper method that calls the RequestDispatcher method.

Page Directive

Defines attributes that apply to an entire JSP page.

Syntax

<%@ page

[ language="java" ]

[ extends="package.class" ]

[ import="{package.class | package.*}, ..." ]

[ session="true|false" ]

[ buffer="none|8kb|sizekb" ]

[ autoFlush="true|false" ]

[ isThreadSafe="true|false" ]

[ info="text" ]

[ errorPage="relativeURL" ]

[ contentType="mimeType [ ;charset=characterSet ]" |

"text/html ; charset=ISO-8859-1" ]

[ isErrorPage="true|false" ]

%>

Examples

<%@ page import="java.util.*, java.lang.*" %>

<%@ page buffer="5kb" autoFlush="false" %>

<%@ page errorPage="error.jsp" %>

Description

The <%@ page %> directive applies to an entire JSP file and any of its static include files, which together are called a translation unit. A static include file is a file whose content becomes part of the calling JSP file. The <%@ page %> directive does not apply to any dynamic include files; see for more information.

You can use the <%@ page %> directive more than once in a translation unit, but you can only use each attribute, except import, once. Because the import attribute is similar to the import statement in the Java programming language, you can use a <%@ page %> directive with import more than once in a JSP file or translation unit.

No matter where you position the <%@ page %> directive in a JSP file or included files, it applies to the entire translation unit. However, it is often good programming style to place it at the top of the JSP file.
Attributes

* language="java"

The scripting language used in scriptlets, declarations, and expressions in the JSP file and any included files. In this release, the only allowed value is java.

* extends="package.class"

The fully qualified name of the superclass of the Java class file this JSP file will be compiled to. Use this attribute cautiously, as it can limit the JSP container's ability to provide a specialized superclass that improves the quality of the compiled file.

* import="{package.class | package.*}, ..."

A comma-separated list of Java packages that the JSP file should import. The packages (and their classes) are available to scriptlets, expressions, and declarations within the JSP file. If you want to import more than one package, you can specify a comma-separated list after import or you can use import more than once in a JSP file.

The following packages are implicitly imported, so you don't need to specify them with the import attribute:

java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*

You must place the import attribute before the element that calls the imported class.

* session="true|false"

Whether the client must join an HTTP session in order to use the JSP page. If the value is true, the session object refers to the current or new session.

If the value is false, you cannot use the session object or a element with scope=session in the JSP file. Either of these usages would cause a translation-time error.

The default value is true.

* buffer="none|8kb|sizekb"

The buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client Web browser. The default value is 8kb. If you specify a buffer size, the output is buffered with at least the size you specified.

* autoFlush="true|false"


Whether the buffered output should be flushed automatically when the buffer is full. If set to true (the default value), the buffer will be flushed. If set to false, an exception will be raised when the buffer overflows. You cannot set autoFlush to false when buffer is set to none.

* isThreadSafe="true|false"


Whether thread safety is implemented in the JSP file. The default value is true, which means that the JSP container can send multiple, concurrent client requests to the JSP page. You must write code in the JSP page to synchronize the multiple client threads. If you use false, the JSP container sends client requests one at a time to the JSP page.

* info="text"

A text string that is incorporated verbatim into the compiled JSP page. You can later retrieve the string with the Servlet.getServletInfo() method.

* errorPage="relativeURL"

A pathname to a JSP file that this JSP file sends exceptions to. If the pathname begins with a /, the path is relative to the JSP application's document root directory and is resolved by the Web server. If not, the pathname is relative to the current JSP file.

* isErrorPage="true|false"


Whether the JSP file displays an error page. If set to true, you can use the exception object in the JSP file. If set to false (the default value), you cannot use the exception object in the JSP file.

* contentType="mimeType [; charset=characterSet ]" |
"text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

Java String Comparison

java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used.

* == Operator
* equals method
* compareTo method

Comparing using the == Operator

The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to. The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision1 {

public static void main(String[] args) {
String name1 = "Bob";
String name2 = new String("Bob");
String name3 = "Bob";
// 1st case
if (name1 == name2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
// 2nd case
if (name1 == name3) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}



Comparing using the equals Method

The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values). The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.

public class StringComparision2 {

public static void main(String[] args) {
String name1 = "Bob";
String name2 = new String("Bob1");
String name3 = "Bob";
// 1st case
if (name1.equals(name2)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
// 2nd case
if (name1.equals(name3)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}



Comparing using the compareTo Method

The compareTo method is used when we need to determine the order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print “name2 follows name1” In the first case and “name1 follows name3” in the second case.

public class StringComparision3 {

public static void main(String[] args) {
String name1 = "bob";
String name2 = new String("cob");
String name3 = "Bob";
// 1st case
if (name1.compareTo(name2) == 0) {
System.out.println("The strings are equal.");
} else if (name1.compareTo(name2) < 0) {
System.out.println("name2 follows name1");
} else {
System.out.println("name1 follows name2");
}
// 2nd case. Comparing Ascii Uppercase will be smaller then Lower Case
if (name1.compareTo(name3) == 0) {
System.out.println("The strings are equal.");
} else if (name1.compareTo(name3) < 0) {
System.out.println("name3 follows name1");
} else {
System.out.println("name1 follows name3");
}
}
}

Saturday, November 8, 2008

Simply Singleton

We all know how objects are instantiated right? Maybe not everyone? Let's go through a quick refresher.

Objects are instantiated by using the new keyword. The new keyword allows you to create a new instance of an object, and to specify parameters to the class's constructor. You can specify no parameters, in which case the blank constructor (also known as the default constructor) is invoked. Constructors can have access modifiers, like public and private, which allow you to control which classes have access to a constructor. So to prevent direct instantiation, we create a private default constructor, so that other classes can't create a new instance.

We'll start with the class definition, for a SingletonObject class. Next, we provide a default constructor that is marked as private. No actual code needs to be written, but you're free to add some initialization code if you'd like.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}
}

So far so good. But unless we add some further code, there'll be absolutely no way to use the class. We want to prevent direct instantiation, but we still need to allow a way to get a reference to an instance of the singleton object.

Getting an instance of the singleton

We need to provide an accessor method, that returns an instance of the SingletonObject class but doesn't allow more than one copy to be accessed. We can manually instantiate an object, but we need to keep a reference to the singleton so that subsequent calls to the accessor method can return the singleton (rather than creating a new one). To do this, provide a public static method called getSingletonObject(), and store a copy of the singleton in a private member variable.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

So far, so good. When first called, the getSingletonObject() method creates a singleton instance, assigns it to a member variable, and returns the singleton. Subsequent calls will return the same singleton, and all is well with the world. You could extend the functionality of the singleton object by adding new methods, to perform the types of tasks your singleton needs. So the singleton is done, right? Well almost.....

Preventing thread problems with your singleton

We need to make sure that threads calling the getSingletonObject() method don't cause problems, so it's advisable to mark the method as synchronized. This prevents two threads from calling the getSingletonObject() method at the same time. If one thread entered the method just after the other, you could end up calling the SingletonObject constructor twice and returning different values. To change the method, just add the synchronized keyword as follows to the method declaration :-

public static synchronized
SingletonObject getSingletonObject()

Are we finished yet?

There, finished. A singleton object that guarantees one instance of the class, and never more than one. Right? Well.... not quite. Where there's a will, there's a way - it is still possible to evade all our defensive programming and create more than one instance of the singleton class defined above. Here's where most articles on singletons fall down, because they forget about cloning. Examine the following code snippet, which clones a singleton object.

public class Clone
{
public static void main(String args[])
throws Exception
{
// Get a singleton
SingletonObject obj =
SingletonObject.getSingletonObject();

// Buahahaha. Let's clone the object
SingletonObject clone =
(SingletonObject) obj.clone();

}
}

Okay, we're cheating a little here. There isn't a clone() method defined in SingletonObject, but there is in the java.lang.Objectclass which it is inherited from. By default, the clone() method is marked as protected, but if your SingletonObject extends another class that does support cloning, it is possible to violate the design principles of the singleton. So, to be absolutely positively 100% certain that a singleton really is a singleton, we must add a clone() method of our own, and throw a CloneNotSupportedException if anyone dares try!

Here's the final source code for a SingletonObject, which you can use as a template for your own singletons.

public class SingletonObject
{
private SingletonObject()
{
// no code req'd
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it's ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

public Object clone()
throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}


private static SingletonObject ref;
}


Preventing direct instantiation

//sample code
package com.test.corejava;

/**
*
* @author seetharam
*/
public class TestSingleton {

private static TestSingleton instance;

// Private constructor suppresses generation of a (public) default constructor

private TestSingleton() {

// logic code is not req'd
}



public static TestSingleton getInstance() {

//acquiring the lock to the class's obj
synchronized (TestSingleton.class) {

if (instance == null) {

instance = new TestSingleton();
}
}

return instance;

}

public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
// that'll teach 'em
}
}


Summary

A singleton is an class that can be instantiated once, and only once. This is a fairly unique property, but useful in a wide range of object designs. Creating an implementation of the singleton pattern is fairly straightforward - simple block off access to all constructors, provide a static method for getting an instance of the singleton, and prevent cloning.

struts-hibernate-integration-tutorial

this is the page where we can get the info like to struts-hibernate Integration in a step by step basis.click here,

JSP Compiler

-we can compile a JSP manually.
here,
The JSP compiler(JSPC) depends on the Web Container.
we take, BEA WebLogic Application Server.

1.goto DOS Shell and run "setEnv.cmd"
2.using cd command move to the JSP file directory.
3.run " java weblogic.jspc -keepgenerated JspOne.jsp "

note : if " -keepgenerated " is not used on above command,
the JSPCompiler removes the .java file which is generated by JSPC.

Friday, November 7, 2008

Serializing and Deserializing Objects

The serialization mechanism in Java provides the means for persisting objects beyond a single run of a Java program. To serialize an object, make sure that the declaring class implements the java.io.Serializable interface. Then obtain an ObjectOutputStream to write the object to and call the writeObject() method on the ObjectOutputStream. To deserialize an object, obtain an ObjectInputStream to read the object from and call the readObject() method on the ObjectInputStream. The following code excerpts illustrate how an object of type MyClass is serialized and deserialized.


1. // Serialize an object of type MyClass
2. MyClass myObject = new MyClass();
3. FileOutputStream fos = new FileOutputStream("myObject.ser");
4. ObjectOutputStream oos = new ObjectOutputStream(fos);
5. oos.writeObject(myObject);
6. oos.flush();
7. oos.close();
8.
9. // Deserialize the object persisted in "myObject.ser"
10. FileInputStream fis = new FileInputStream("myObject.ser");
11. ObjectInputStream ois = new ObjectInputStream(fis);
12. MyClass myDeserializedObject = (MyClass)ois.readObject();
13. ois.close();

Lines 1-5 serialize the object myObject of type MyClass. On Line 3, the file output stream fos is created for the file named myObject.ser. The object is actually persisted in this file on Lines 5-7. Lines 9-13 read the object back from the file myObject.ser. If you list the files in the directory where this code's .class file is stored, you will see a new file called myObject.ser added to the listing. The Lines 1-7 and 9-13 can be in two completely different processes run at different times.

Thursday, November 6, 2008

What is the purpose of finalization ?

protected void finalize() throws Throwable

* Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.
The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

* The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.
The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.
After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.
The finalize method is never invoked more than once by a Java virtual machine for any given object.

* Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

* While exception handling if exception is thrown programme will abort abnormally but it can leads to some problamatic situation..hence we have to ensure some code will always run whtever happen..finalization does so. Some useful tasks that we have to do ( cleaning up some resources or closing some connection or socket etc) we can gurantee it will be done by simply putting it in finally block.

* It will run always (Unless System.exit() is not called) and
hence future problem can be handled.

* finally block, finalize() - performed by the JVM,before calling GC

Wednesday, November 5, 2008

A sample code of "Thread implements Runnable"

package com.test;

/**
*
* @author seetharam
*/

public class TestThread implements Runnable{

Thread myThread;

public TestThread()
{
System.out.println("in init() -- starting thread.");
myThread= new Thread(this);
myThread.start();
}


public void run()
{
int i=0;
for(;;)
{

System.out.println("At " + i + " and counting!");
try {myThread.sleep(1000);
i++;
}
catch (InterruptedException e ) {}

}
}
public static void main(String a[]){
TestThread obj=new TestThread();

}
}

Sunday, November 2, 2008

can a lock be acquired on a class ? reply : Yes, we can.

By using synchronize block on obj.here, a ClassName.class can return an object


package com.test;

/**
*
* @author thanooj
*/

public class Emp {

private int eno;
private String ename;
private double sal;
public Emp(int eno,String ename,double sal){
this.eno=eno;
this.ename=ename;
this.sal=sal;
}
public int getEno(){
return eno;
}
public String getEname(){
return ename;
}
public double getSal(){
return sal;
}
}
``````````````````````````````````````````````````
package com.test;

/**
*
* @author thanooj
*/

public class Dept {
private int dno;
private String dname;
private Emp emp;
public Dept(int dno,String dname){
this.dno=dno;
this.dname=dname;
}
public int getDno(){
return dno;
}
public String getDname(){
return dname;
}
public Emp getEmp(){
return emp;
}

public void addEmp(Emp emp){
synchronized(Emp.class){
this.emp=emp;

// our Complex Operations

}


}
}
```````````````````````````````````````````````````

package com.test;

/**
*
* @author thanooj
*/

public class TestLockAClass {
public static void main(String a[]){

Emp emp=new Emp(1,"rama",50000.01);
System.out.print(emp.getEno()+" "+emp.getEname()+" "+emp.getSal());
Dept dept =new Dept(10,"developer");
dept.addEmp(emp);
System.out.println();
System.out.print(dept.getDno()+" "+dept.getDname());
System.out.println();
System.out.println(dept.getEmp().getEno()+" "+dept.getEmp().getEname()+" "+dept.getEmp().getSal());
}
}

output
--------
1 rama 50000.01
10 developer
1 rama 50000.01

what is a transient variable

Serialize means to keep the state of an object i.e when you serialize an object you actually capture the current state of object in binary form, then you can write it in FileOutputStream or can send it to Socket's OutputStream.
De-Serialize means to read that binary data from FileInputStream or Socket's InputStream and convert it in to original Object.
In Java WriteObject() and ReadObject() methods used for Serialize and De- Serialize.

Marshalling and UnMarshalling:
Marshalling means to send the data on wire and UnMarshalling means to get the data from wire.

Marshalling :marshals means to packup the information. The skeleton on the ser ver marshals the parameters and calls methods on remote object if any.
Un-Marshalling :un-marshals means to un-pack the information.The stub un-marshals the results and gives the results to the clients.

Transient variable,can not be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can not be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null

You use the transient keyword to indicate to the Java virtual machine that the indicated variable is not part of the persistent state of the object. Variables that are part of the persistent state of an object must be saved when the object is archived.

Java enum : Creating an Enum

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/**
*
* @author thanooj
*/

enum OperatingSystems {windows, unix, linux, macintosh}


public class TestSampleEnum {

public static void main(String args[])
{
OperatingSystems os;

os = OperatingSystems.windows;
switch(os) {
case windows:
System.out.println("You chose Windows!");
break;
case unix:
System.out.println("You chose Unix!");
break;
case linux:
System.out.println("You chose Linux!");
break;
case macintosh:
System.out.println("You chose Macintosh!");
break;
default:
System.out.println("I don't know your OS.");
break;
}
}
}
-----------------------------------------------------------------------------

import java.io.IOException;
import java.io.PrintStream;

enum Grade { A, B, C, D, F, INCOMPLETE };

class Student {

private String firstName;
private String lastName;
private Grade grade;

public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getFirstName() {
return firstName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getLastName() {
return lastName;
}

public String getFullName() {
return new StringBuffer(firstName)
.append(" ")
.append(lastName)
.toString();
}

public void assignGrade(Grade grade) {
this.grade = grade;
}

public Grade getGrade() {
return grade;
}
}

public class TestEnum {

private Student student1, student2, student3;

public TestEnum() {
student1 = new Student("Brett", "McLaughlin");
student2 = new Student("Ben", "Rochester");
student3 = new Student("Dennis", "Erwin");
}

public void testGradeAssignment() throws IOException {
student1.assignGrade(Grade.B);
student2.assignGrade(Grade.INCOMPLETE);
student3.assignGrade(Grade.A);
}

public void listGradeValues(PrintStream out) throws IOException {
Grade[] gradeValues = Grade.values();

// for loop
for (int i=0; i out.println("Allowed value: '" + gradeValues[i] + "'");
}

// for/in loop
for (Grade g : gradeValues ) {
out.println("Allowed value: '" + g + "'");
}
}

public void testSwitchStatement(PrintStream out) throws IOException {
StringBuffer outputText = new StringBuffer(student1.getFullName());

switch (student1.getGrade()) {
case A:
outputText.append(" excelled with a grade of A");
break;
case B: // fall through to C
case C:
outputText.append(" passed with a grade of ")
.append(student1.getGrade().toString());
break;
case D: // fall through to F
case F:
outputText.append(" failed with a grade of ")
.append(student1.getGrade().toString());
break;
case INCOMPLETE:
outputText.append(" did not complete the class.");
break;
default:
outputText.append(" has a grade of ")
.append(student1.getGrade().toString());
break;
}

out.println(outputText.toString());
}

public static void main(String[] args) {
try {
TestEnum tester = new TestEnum();

tester.testGradeAssignment();
tester.listGradeValues(System.out);
tester.testSwitchStatement(System.out);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Thursday, October 30, 2008

JVM's Execution Engine - Interpreter + JIT Compiler

//code
int a=1,b=2;


here by using interpreter
let us assume that , it will take 2 sec for doing execution of one statement.(line by line)
so .... it will take 2+2 = 4 sec for the beloved 2 statements.

//code
print a;
print b;
`````````````````````````````````````````````````````````````````
but... in loop or repeated statements execution... like ...

//code
loop 10 times
print a;

here by using interpreter ,
it will take 2 sec for each Iteration.
therefore , 2*10=20 sec

here we come across JIT compiler .
it will compile whole loop statements and store into memory.for this it will take 2 sec.
and for executing loop ,it takes 2 sec.
totally 4 sec . where as by using interpreter we do same ,in 20 sec

--------------------------------------------------------------------------------------------------------

in c,c++ like compiling languages ..
we convert them to intermediate form ... and immediate for execution.
here compiled file is not similar to text file.and it may contain pointer references.
there is a scope for virus attack.

- here ,Java.
we have bytecode as intermediate form ...which is input to JVM's execution engine - Interpreter,here we come across above discussed concepts in,Interpreter + JIT Compiler.

Wednesday, October 29, 2008

JDBC Driver Types




JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver (Middleware)
Type 4: All Java/Native-protocol driver (Pure)

4 types of jdbc drivers are elaborated in detail as shown below:

Type 1 JDBC Driver - JDBC-ODBC Bridge driver


The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.

Functions

* Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver.
* Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source.
* Client -> JDBC Driver -> ODBC Driver -> Database
* There is some overhead associated with the translation work to go from JDBC to ODBC.

Advantage

The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC drivers are already available.

Disadvantages

1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.

Type 2 JDBC Driver - Native-API/partly Java driver



The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.


Functions
* This type of driver converts JDBC calls into calls to the client API for that database.
* Client -> JDBC Driver -> Vendor Client DB Library -> Database


Advantage

The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.

Disadvantage


1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet(protocol conversion logic resides with client machine).
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe.

Type 3 JDBC Driver - All Java/Net-protocol driver

Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.


Functions

* Follows a three tier communication approach.
* Can interface to multiple databases - Not vendor specific.
* The JDBC Client driver written in java, communicates with a middleware- net-server using a database independent protocol, and then this net server translates this request into database commands for that database.
* Thus the client driver to middleware communication is database independent.
* Client -> JDBC Driver -> Middleware-Net Server -> Any Database


Advantage

1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
5. The 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.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.

Disadvantage

It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server
(This differs from the type 4 driver in that the protocol conversion logic resides not at the client, but in the middle-tier).

Type 4 JDBC Driver - Native-protocol/all-Java driver



The Type 4 uses java networking libraries to communicate directly with the database server.


Functions

* Type 4 drivers are entirely written in Java that communicate directly with a vendor's database, usually through socket connections. No translation or middleware layers are required, improving performance.
* The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server.
* Completely implemented in Java to achieve platform independence.
* e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thin URL format.
* Client Machine -> Native protocol JDBC Driver -> Database server


Advantage

1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. 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.
3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

Disadvantage

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

Monday, October 13, 2008

Top Nine Errors Java Programmers Make

* A .java source file can contain more than one class but it can contain atmost one Top level class (or interface) definition that is public and the name of the source file must be same as that of the public class (or interface).
* Static methods cannot be overridden but can be hidden if they are not final (Read about Overriding vs Hiding here).
* The objects created in the String pool are not subjected to GC until the class is unloaded by the JVM.
* Only methods or code blocks can be marked “synchronized”.
* Local classes cannot access non-final variables.
* -0.0 == 0.0 is true.
* Collection (singular) is an Interface, but Collections (plural) is a helper class.
* continue must be in a loop (e.g., for, do, while). It cannot appear in case constructs.
* Instance initializers are executed only if an object is constructed.

Thursday, October 2, 2008

ArrayIndexOutOfBoundsException in Java



package com.index;

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

public class ListIndexTest {

 /**
  * @param args
  */
 public static void main(String[] args) {

  List<String> list = new ArrayList<String>();
  int indexOf = 0;
  try {
   indexOf = list.indexOf("test");
   System.out.println(list.remove(indexOf));
  } catch (ArrayIndexOutOfBoundsException e) {
   e.printStackTrace();
  }
  try {
   // avoiding exception by condition check.
   indexOf = list.indexOf("test");
   if(indexOf >= 0){
    System.out.println(indexOf + " "+ list.remove(indexOf));
   }else{
    System.out.println("index of test : "+indexOf);
   }
  } catch (ArrayIndexOutOfBoundsException e) {
   e.printStackTrace();
  }
  list.add("test");
  list.add("rest");
  list.add("quest");
  list.add("test");
  indexOf = list.indexOf("test");
  System.out.println(indexOf + " "+ list.remove(indexOf));
  indexOf = list.indexOf("test");
  if(indexOf >= 0){
   System.out.println(indexOf + " "+ list.remove(indexOf));
  }
 }

}


output:

java.lang.ArrayIndexOutOfBoundsException: -1
 at java.util.ArrayList.elementData(ArrayList.java:371)
 at java.util.ArrayList.remove(ArrayList.java:448)
 at com.index.ListIndexTest.main(ListIndexTest.java:17)
index of test : -1
0 test

2 test

Hibernate and JDBC

Following link has very good explanation about hibernate and JDBC as well as it explains difference between hibernate and JDBC

Tuesday, September 30, 2008

JDBC connectivity with MySQL

import java.sql.*;
public class MySQLConn {

public static void main(String[] args) {
System.out.println("MySQL Connect Example.");

Connection conn = null;
String url = "jdbc:mysql://localhost:3306/mydb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";

try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,userName,password);
Statement stmt= conn.createStatement();
System.out.println("Connected to the database ");
String query="select * from mytab";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
-----------------------------------------------------
Note : We need to add a jar to the classpath.
ie., for Oracle - ojdbc14.jar
     for MySQL -  "mysql-connector-java-3.1.12-bin"

In the above code : mydb is the database name

Java - main() method - in shot

Let us think about

public static void main(String args[]){
}

here,
public - specified for java interpreter to access the class
from out side of the class.
static - we need to call main() method before the object creation
of that class.
instance methods can be called after instantiating the class
and by using object reference variable.
void - main() method which return nothing to caller JVM
args[] - this is a String array ,which is used for giving inputs
to our program while running is
eg: java SampleClass Kalathuru Thanooj JavaTemple
for( int i=0; i
System.out.println(args[i]);
}

Note: we can also override the main() method.