Friday, June 22, 2007

Threads

States of thread
A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below.
Ready State A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state.
Running State A thread is said to be in running state when it is being executed. This thread has access to CPU.
Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now.
Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states - sleeping, suspended, blocked, waiting for monitor.

0 A dead Thread cannot be restarted.
0 If you call its start() method after its death, IllegalThreadStateException will be thrown.
0 Even the Thread is dead, but you still can call its other method. Why? Simple, the Thread is just another Java Object. For example, if you call its run() method again, it will be just a sequential procedure call, no concurrent execution at all.

thread.join(): The effect of calling jobT.join() statement is that current thread waits for jobT to complete.

thread.isAlive(): The isAlive method returns true if the thread has been started and not stopped. If the isAlive method returns false, you know that the thread either is a New Thread or is Dead.

inner, nested, anonymous classes

0 There is no such thing as a static inner class. There are top-level classes and nested classes, and nested classes are by definition divided into static and inner.
0 If it is static, it is not inner class, you can use it just as top-level class, but put a qualifier as EncloseingClass.EnclosedClass.
0 If inner class is a member of enclosing class, it must be attached to an instance of the Enclosing class, something like new EnclosingClass().new EnclosedClass().
0 Local and anonymous classes are also inner classes, they can be defined in methods, initializers, which will be local to that enclosing scope.
0 Since the scope can be instance or static, Local and anonymous classes can be defined in an instance or a static context.

0 inner class in an interface?
interface IFace {
public class X { //It is not member inner class
void method_Of_X() {
System.out.println("Without static modifier, it is still static nested class.");
}
}

static class S { // static nested class.
void method_Of_S() {
System.out.println("static nested class.");
}
}
}
Conclusion: All classes defined in an interface are implicitly static

0Anonymous class always extends the class or implements the interface after the keyword new. I assume that extends or implements can only be implicit, in case of anonymous classes.

0 An anonymous class object can access static and instance fields when it has an associated instance of the enclosing class (i.e. defined in a instance method).
0 An anonymous class can only access static fields when it is in a static context (i.e. defined in a static method).
0 What it can't access is local variables (unless they are declared final). Attention: parameters passed to the method are treated the same as local variables, since it is passed by value and a local copy are really being used.
0 local class defined in a method can access final local variables.

Static, Interface and abstract class

Implicit access modifiers in interface:

>>All the variables defined in an interface must be static final, i.e. constants. Happily the values need not be known at compile time. You can do some computation at class load time to compute the values. The variables need not be just simple ints and Strings. They can be any type.
>>All methods in an interface are implicitly declared public and abstract. All variables in an interface must be constants. They are implicitly declared public static final.

>>Interface is abstract, but not vice versa. There should be nothing implemented in interface. Abstract class can be partially implemented.
>>A class can only extend one class; abstract class is included.
>>A class can implement multi interfaces.

Can abstract class and interface have static method:
Ex:
abstract class A {
// OK
static void doSomething() {
}

// illegal combination of modifiers: abstract and static
//abstract static void doOtherthing();
}

interface B {
// modifier static not allowed here
// static void doSomething();
}

static and interface:
1) Inner interfaces are implicitly static, no matter you put static modifier or not. Attention: inner interfaces are very rarely used.
2) Outer interface are NOT static, just like outer class.
3) All members (attributes & methods) of interface are implicitly public.
4) All attributes defined in interface are implicitly static and final.
5) All methods defined in interface are NOT static.
6) All classes defined in an interface are implicitly static

abstract class cannot be instantiated.
// The following code will not be compilable
abstarct public class A{

}
// A a = new A();
// a.aMethod();

What kind of Java methods does not participate polymorphism?

Polymorphism for Java method is always there except the following three situations:

The method is declared as final
The method is declared as private
The method is declared as static


In those three cases, static binding will be performed by the compiler. Compiler does not have the knowledge, nor care about the method was, is, or will be overridden by none, one, or many subclass(es). The decision is made by the runtime, which is called dynamic binding.

Thursday, June 21, 2007

Q. When should I use inheritance, when aggregation?

A: They are Two different relationships!

He is a human, human has a heart!

ISA: inheritance //He is a human,
HASA: aggregation //human has a heart

static method override

A subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method. A subclass can hide a static method in the superclass by declaring a static method in the subclass with the same signature as the static method in the superclass.

Ex:
public class Test {
public static void main(String[] args){
baseClass bb = new subClass();
subClass1 ss = new subClass();

ss.testme(); //output:This is inside the sub class
bb.testme(); //output:This is inside the sub class

//Conclusion: U are able to override the testme method here.

ss.testmeStatic(); //output:This is inside the sub class static
bb.testmeStatic(); //output:This is inside the base class static

//Conclusion: U are not able to override the testmeStatic method here.
}
}
class subClass extends baseClass{
public void testme(){
System.out.println("This is inside the sub class");
}
public static void testmeStatic(){
System.out.println("This is inside the sub class static ");
}
}
class baseClass{
public void testme(){
System.out.println("This is inside the base class");
}
public static void testmeStatic(){
System.out.println("This is inside the base class static ");
}
}

Difference between new String("hello") and "hello"

public class test
{
public static void main(String[] args)
{
String a = new String("hello");
String b = new String("hello");

if(a == b)
System.out.println("Equal");
else
System.out.println("Not Equal");

String c = "hello";
String d = "hello";
if(c == d)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

i expected i will get since a, b, c and d are reference to difference objects (or maybe i am wrong)
"Not Equal"
"Not Equal"

however, what i get is
"Not Equal"
"Equal"

isnt that c and d are refrence to different objects?

Strings are pooled and shared in Java, for efficiency reasons. By constructing a String object with the new keyword, you are explicitly telling the JVM not to the use strings from the pool. Therefore, for String a and b, they are referencing to 2 different strings (that is, 2 strings that are located on different addresses in the memory), whereas for c and d, they are referencing the to the same string located on the same address in memory.



== compares the memory addresses and not the value of the variables.

equals
public boolean equals(Object obj)Indicates whether some other object is "equal to" this one.
The equals method implements an equivalence relation:

It is reflexive: for any reference value x, x.equals(x) should return true.
It is symmetric: for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
It is transitive: for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
For any non-null reference value x, x.equals(null) should return false.

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true).

Remember

final variable (variables), they are of type static or instance, must be initialized explicitly. final instance variables can also be initialized by every constructor.Three choices to make the code right:

public class Test{
static int sn;
int n;
final static int fsn; //wrong
final int fn; //wrong
}


public class Test{
static int sn;
int n;
final static int fsn = 3;
final int fn = 6;
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}
{fn =8;}
}

public class Test{
static int sn;
int n;
final static int fsn;
final int fn;

static {fsn=6;}

Test(){
fn =8;
}
Test(int pn){
fn =pn;
}
}

A subclass cannot override methods that are declared final in the superclass (by definition, final methods cannot be overridden). If you attempt to override a final method, the compiler displays an error message similar to the following and refuses to compile the program:"

a subclass cannot override methods that are declared static in the superclass. In other words, a subclass cannot override a class method.

transient and static variables are not serializable.

we can use transient and static to modify the same variable.

The default constructor implicitly generated by Java compiler should have the same accessibility as the class. i.e. public class will have a public default constructor

Q. Can we declare an object as final?

final variables cannot be changed.
final methods cannot be overridden.
final classes cannot be inherited. However, there is something easily to be confused. There is no final Object in Java. You cannot even declare an Object in Java, only Object references. We only can have final object reference, which cannot be changed. It is like that the address of your house cannot be changed if it is declared as final. However, you can remodel your house, add a room, etc. Your house is not final, but the reference to your house is final. That is a little confusing. By the way, use finals as much as possible, but do not overuse them of course. It is because compiler knows they are not going to change, the byte code generated for them will be much more efficient.

What is modifier for the default constructor implicitly generated by Java compiler?

The default constructor implicitly generated by Java compiler should have the same accessibility as the class. i.e. public class will have a public default constructor, package "friendly" class will have package "friendly" constructor, unless you explicitly define it otherwise.

Does Java initialize static variable first when we instantiate an Object?

Wrong question! Please do NOT mix static field initialization with Object construction or instantiation!

>>static field initialization happens at class loading time, it only happens once, and once only. It might be changed long before your object instantiation time!
>>When you compile and run a toy program, it might look correct. However, the real world programming is NOT a toy!
>>Someone might think "what the article said should be correct at least once, at least correct at the first Object is instantiated." No, that is not necessary true either, since you might call on static method of that class long before the first Object is instantiated. The static value has been initialized and changed long before the first Object is instantiated.

What are the variable initialization rules in Java?

Member variables (both static and instance) are initialized implicitly by default:
Most primitives except boolean are default initialized to zero, not null!
boolean variables are default initialized to false, not zero, not null!
Only object references are default initialized to null!
Final varibles must be initialized explicitly in declaration or constructors (instance final variable.)

Local varibles are not initialized
They are not default intialized to anything, unless programmer initialize them explicitly!
It is not compilable if you use them before assign them a value!

In Java, everything is pass-by-value

Some people will say incorrectly that objects are passed "by reference." In programming language design, the term pass by reference properly means that when an argument is passed to a function, the invoked function gets a reference to the original value, not a copy of its value. If the function modifies its parameter, the value in the calling code will be changed because the argument and parameter use the same slot in memory. The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode -- pass by value -- and that helps keep things simple.

Wednesday, June 20, 2007

How to properly dispose of (close) JDBC resources

There is only one right way to close JDBC resources properly and it includes all of the following.

you must call the close method
you must close the resources in the opposite order to that in which you opened them. Close ResultSets first, Statements second and Connections last
you must close all your resources in a finally block

Example 1 - the correct way
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = // get connection
ps = conn.prepareStatement(sqlString);
rs = ps.executeQuery();

}catch(SQLException sqle){
// whatever exception handling is appropriate for your program for now...
sqle.printStackTrace();
}finally{
if(rs!=null){
try{
rs.close();
}catch(SQLException closeRsEx){
// you should probably log this exception
}
}
if(ps!=null){
try{
ps.close();
}catch(SQLException closePsEx){
// you should probably log this exception
}
}
if(conn!=null){
try{
conn.close();
}catch(SQLException closeConnEx){
// you should probably log this exception
}
}
}
Please note that the point of the above example is not to say that all your JDBC code must only go into one method, the point is to demonstrate all the steps that go into making sure that we close our JDBC resources properly. Namely; we call close on all our JDBC objects, we do it in the inverse order from creation, we close all our resources in a finally block to ensure that our closing code is called. You should be closing your resources as soon as you are done with them.

Please also note that Statements were mentioned but a PreparedStatement was used. The rules to follow when closing JDBC resources regarding Statement apply just as much if not moreso to the sub-interfaces of Statement (PreparedStatement and CallableStatement).

Common mistakes

Sometimes the best way to learn what is right is to study what is wrong when mistakes are made. So in this light are a few examples of commonly seen mistakes in code dealing with JDBC resources.

One mistake is to set the Connection, Statement and ResultSet variables to null instead of calling the close methods. This seems to spring from a notion that then the Java garbage collector will "deal" with it and all will be fine. This is though a mistake for two reasons. One you may be leaving resources tied up locally for longer than they have to be. Two you not be closing resources on the database properly if at all thus causing all of the database server related problems listed previously. To avoid this mistake you must call close on all the instances of Connection, Statement and ResultSet you use.

A second mistake often seen is to only close some of the resources like Connection but not ResultSets or Statements. This one is based on the theory that closing the Connection is "good enough" and that the JDBC driver will deal with the rest. This one is a mistake for three reasons. One you will probably leaving resources locally and on the database tied up for longer than is necessary (thus degrading performance). Two, it relies on the JDBC driver and database implicitly cleaning up for you which may or not happen correctly. It is better to explicitly call close than implicitly. Three it may not work at all in some scenarios, for example with a ConnectionPool where the connections are not in fact ever closed but recycled.

Replace "." using regexp

String.replaceAll takes a regexp as argument, and a single dot means any character in the regexp world. The solution to replacing a single dot is to escape the dot. A backslash is used for escaping in regular expressions, but we need to use two backslashes. One to escape the dot, and another one to escape the backslash (since we want to place it within a string).

String text = "..text with.. dots..";
String withoutDots = text.replaceAll("\\.", "");

Friday, June 1, 2007

Difference between error and an exception?

An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).