Wednesday, May 31, 2006

comparinng Integer objects as String

Integer i= new Integer("10");
if (i.toString() == i.toString())
System.out.println("Equal");
else
System.out.println("Not Equal");


The output is "Not Equal". Certainly Strange. See the explanation.

The toString() method returns the String equivalent of this String object. It creates a new object each time it is called. The == operator compares the bit patterns of the two object references and not the actual String contents. Thus the comparison returns false, theelse statement is executed, and "Not Equal" is printed out.

Character literals

For char literals, a single character is enclosed in single quotes. You can also use the prefix \u followed by four hexadecimal digits representing the 16-bit Unicode character: '\u004E', 'A', 'a'.

Octal & Hexadecimal

Octal literals begin with zero and only digits 0 through 7 are allowed.

For instance:011

Hexadecimal literals begin with 0x or oX, the digits allowed are 0 through 9 and a through f (or A through F).

For instance: 0x0001;

Difference: toString & System.out.println()

Remember that whenever you pass an object to the System.out.println() method, the object’s toString() method is automatically called. Because of polymorphism, this method is always called on the runtime type of the object, which in this case is a String.

Assertion

An assertion is a statement containing a boolean expression that is assumed to be true when the statement is executed. The system reports an AssertionError if the expression evaluates to false. It is used for debugging purposes:

assert(a > 0); // throws an AssertionError if a <= 0

Assertions can be in two forms:

assert Expression1 ;
assert Expression1 : Expression2 ;

Expression1 should always result in a boolean value.Expression2 can be anything that results in a value. The value is used to generate a String message that displays more debugging information.

Example:
class AssertionTest{
int a ;
public void func(){
assert (a < 0): "a is positive" ;
// Remaining code
}
}

In the above code, the assertion expression is true if a is negative. If a is positive, an AssertionError is thrown with the message "a is positive."Assertions are disabled by default. To compile with assertions enabled, you need to use the source 1.4 flag:javac -source 1.4 Test.javaTo enable assertions at runtime, use the -enableassertions or -ea flags.For selective disabling of assertions at runtime, use the -da or –disableassertions flags.For enabling assertions in the system classes, use the -esa or -dsa flags. Assertions can also be enabled or disabled on a package basis.

Arrays

When we declare an array variable, the code creates a variable that can hold the reference to an array object. It does not create the array object or allocate space for array elements. It is illegal to specify the size of an array during declaration. The square brackets may appear as part of the type at the beginning of the declaration or as part of the array identifier:

int[] i; // array of int
byte b[]; // array of byte
Object[] o, // array of Object
short s[][]; // array of arrays of short

Saturday, May 27, 2006

java.lang.Runtime

Following are the few methods in Runtime class -

Process exec(String command) --> Executes the specified string command in a separate process.

Process exec(String[] cmdarray) --> Executes the specified command and arguments in a separate process.

Process exec(String[] cmdarray, String[] envp) --> Executes the specified command and arguments in a separate process

Process exec(String[] cmdarray, String[] envp, File dir) --> Executes the specified command and arguments in a separate process with the specifiedenvironment and working
directory.

Process exec(String command, String[] envp) --> Executes the specified string command in a separate process with the specified environment.

Process exec(String command, String[] envp, File dir) --> Executes the specified string command in a separate process with the specified environment and working directory.

Heap & Stack memory

Space for objects created with the new operator are allocated in the heap. Method arguments or local variables of primitive types are created on the stack. Objects created in the heap have a longer lifetime.

Objects are kept on the heap, and since objects can contain instance variables of primitive types, these primitive variables are kept on the heap as well.

Wednesday, May 24, 2006

Object funda

1). An object can be finalized only once.
2). An object has exactly one lock.
3). The lock of an object is independent of lock of its class.
4). A thread can reacquire the lock on the same object.
5). A thread can have locks on different object at the same time.

common mistake between (++j) & (j++)

Following is the example;

example 1:

int i = 4;
int j = 6;

int k = ++i + j;
System.out.println(k);

The output of above will be 11. That is, it first increments the value of i by 1 and then adds to j. Now consider the following example -

example 2:

int i = 4;
int j = 6;

int k = i++ + j;
System.out.println(k);

The output of above will be 10. Because, first it adds up the value of i & j and then it increments the value of i by 1. That is, at that particular line the value of i remains same. It becomes effective from the next line onwards.

while (false) cannot be written

while (false) {}

The above code will never compile. It will throw an compiler exception that code cannot be reached.

Overloading & Overridding

1). static methods cannot be overridden.
2). private methods cannot be overridden.
3). private methods can be overloaded.
4). The overriding method cannot be less public than the overridden method. The overriding method should not throw new or broader checked exceptions that are not declared by the original method.
5). Methods declared as final cannot be overridden by subclasses. Even though constructors can be overloaded, they cannot be overridden because they are not inherited.
6). A final method can be overloaded.
7). A static method can be overloaded.
8). You can override only instance methods that you inherit. Because you never inherit private methods, they cannot be overridden.
9). A final method cannot be overridden even though it is inherited.

String comparison

One should not compare the String as follows -
string1 == string2

I will explain you with the example -
example 1 :

String a = "java";
String b = "java";
if (a == b)
System.out.println("campared using ==");
if(a.equals(b))
System.out.println("campared using equals()");

In this cases both the println statements will execute. Now consider the following example -

String a = "java";
String b = new String("java");
if (a == b)
System.out.println("campared using ==");
if(a.equals(b))
System.out.println("campared using equals()");

In this case the output will be "campared using equals()". This is bacause String objects are immutable. That means String objects cannot be modified. When we try to modify it the JVM internally creates the new String object which is hidden from us. In example 2, (a == b) compares the string object and (a.equals()) compares the object contents.
Whenever you require the String object to be modified later intead use StringBuffer. StringBuffer object is muttable. we can modify the content using append() method.

Garbage Collector

The JVM usually runs the garbage collector when the level of available memory is low. However, the garbage collector cannot ensure that there will always be enough memory. If there is not enough memory even after the garbage collector reclaims memory, the JVM throws an OutOfMemoryError exception. Note that the JVM will definitely run the garbage collector at least once before throwing this exception. While you can request that the garbage collector run, it is important to note that you can never force this action.

An object is eligible for garbage collection when no live thread can access it.An object can become eligible for garbage collection in different ways:

1> If the reference variable that refers to the object is set to null, the object becomes eligible for garbage collection, provided that no other reference is referring to it.
2> If the reference variable that refers to the object is made to refer to some other object, the object becomes eligible for garbage collection, provided that no other reference is referringto it.
3> Objects created locally in a method are eligible for garbage collection when the method returns, unless they are exported out of the method (that is, returned or thrown as an exception).
4> Objects that refer to each other can still be eligible for garbage collection.

why an abstract method can't be private ???

An abstract method's are mean't to be overridden in the concreate class. A private method can't be overridden. So declaring a method as abstract and private doesn't make any sense.

type cannot be deferenced

e.g.,
int i = 10;
String con = i.toString();

We cannot do this because "i" is not an object, it's a premitive datatype. And toString() method is in defined in java.lang.Object.
If we want to use it any how then following code can be used -

int i = 10;
String con = i + "";

Anonymous Class

Unlike mormal classses Anonymous classes don't have name (therefore anonymous class). Because they don't have name, it's not possible to refer them. Therefore we have to declare them when we create them. Following is the famous example -

JButton normalButton = new JButton();

normalButton.addActionListener( new ActionListener() {

public void actionPerformed ( ActionEvent e )
{
normalText.setText("Hi text");
}

} );


Anoymous classes are created using "new" operator and without "class" keyword.

Monday, May 22, 2006

While Declaring variables

The following modifiers can be used when declaring a variable: public, private, protected, final, transient, volatile.

Constructors

1). When no constructors have been declared in a class, the compiler automatically generates a default constructor. The default constructor has no arguments and inherits the same access modifier as the class.

2). If you invoke the default constructor of your class and the superclass does not have a constructor without any arguments, your code will not compile. The reason is that the subclass default constructor makes an implicit call to the no-argument constructor of its superclass.

Final Variable

Final variable can only be assigned a value once.

Static Inner Class

Outer out = new Outer();
Outer.non_static ns = out.new non_static();
Outer.inner in = new Outer.inner();

where,
Outer --> Outer class
non_static --> inner non static class
inner --> inner static class
For calling non static inner class we require the instance of the outer class and for calling static innner class doesn't require the instance of the outer class.