Wednesday, June 14, 2006

inner class inside method

Yes, we can have an inner class inside a method and final variables can be accessed.

Transient & Volatile Modifiers

Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized.

Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

final, finalize() and finally ???

final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can’t be overridden. A final variable can’t change from its initialized value.

finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection.

finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

Thursday, June 01, 2006

Unchecked exception

Any exception that extends from RuntimeException is considered an unchecked exception. Unchecked exceptions do not have to be handled in a catch block, though they can be. The compiler never forces you to handle unchecked exceptions.

Checked exception

An exception that the compiler forces code to handle. You can usually accomplish this by using a try/catch block. All checked exceptions inherit from the java.lang.Exception class but do not extend the java.lang.RuntimeException class.

User defined Exceptions

Whenever you create your own exceptions, you follow some common steps.

Although you can certainly add your own methods and variables, it is more common to simply use the inherited methods defined in your superclasses. First, you want to define at least two constructors: a default, no-argument constructor, and a constructor that accepts a String object as a parameter. The latter constructor allows you to pass the message that you want this exception type to return from the getMessage() method. Normally, all these constructors do is invoke the superclass constructors, located in Exception.

Abstract classes

Technically, an abstract class does not have to contain any abstract methods. This is rather unusual, but in such a case, the class simply cannot be instantiated.

> If a subclass does not override all abstract methods, it also must be declared an abstract class. If you try to compile the such class without overriding all abstract methods, the compiler alerts you to this and tells you to either override them or declare this class abstract as well.
> No abstract methods can be declared as private, final, or static.

super() method

The first line of every constructor must call another constructor. If you do not explicitly call another constructor with this() or super(), he compiler always makes super() with no parameters the first line of a constructor.

public ClassName()
{
System.out.println(“Hello!”);
}
public ClassName()
{
super();
System.out.println(“Hello!”);
}

This happens because it is essential that your superclass be initialized before your subclass.

Object casting

When you are performing object casting, the best practice is to incorporate the instanceof operator into your code. First, use instanceof to be sure that the target object is the type you expect; only then should you perform the cast. This ensures that you are never trying to cast an object illegally, and you can be sure to avoid those pesky runtime errors.

Virtual Method Invocation

Although methods can take advantage of virtual method invocation, variables cannot. Variables are always bound to the reference type. This is important to understand if you provide the same variable name in both a superclass and a subclass.

public class SuperVariableDemo
{
public String str = “Superclass”;
}
public class SubVariableDemo extends SuperVariableDemo
{
public String str = “Subclass”;
public static void main(String[] args)
{
SuperVariableDemo sd = new SubVariableDemo();
System.out.println(sd.str);
}
}

The output will always be Superclass even though the runtime type is SubVariableDemo. Remember that instance methods are always bound to the runtime type, and instance variables are always bound to the reference type. If you commit this to memory right now, you will avoid some strange and pesky bugs in the future!

The reference type rule for methods:

The rule is that if you try to call a method via an object reference, that method must be defined in the class of the reference type to begin with. You simply cannot directly call a method solely defined in a subclass if you reference that object with the superclass type.

SuperClass variable

If you define a variable in your subclass with the same name as a variable in your superclass, the superclass variable is hidden. This can lead to hard-to-find errors, so be careful about doing this. The JVM always uses the variable that is the “most local” to the object. If a variable x is defined in both the superclass and the subclass, a subclass instance “sees” only its own variable.

Constructor chaining

Constructors can be “chained” together, allowing one constructor to invoke another and so on until an “ultimate constructor” executes. To chain constructors, you use the this keyword to represent the constructor invocation.

Example of Constructor chaining:

public class ColoredLightBulb2
{
private boolean lit;
private String color;

public ColoredLightBulb2()
{
this(“white”);
}
public ColoredLightBulb2(String color)
{
this.color = color;
}


Two rules for Constructor chaining:

First, if you do invoke another constructor in this fashion, that invocation must come on the first line of your constructor.
The second rule of constructor chaining is that you can explicitly call only one constructor from within another constructor. It is illegal to call another constructor more than once. You could expand the first rule to say that you can invoke another constructor only on the first line and never again in the same constructor body.

Static methods

Static methods cannot access instance methods or instance variables:

Static methods have no such concept. If you think about it, that makes complete sense. Remember that a static method does not require an object to be invoked; normally, static methods are invoked using the ClassName.staticMethodName() syntax. Because a static method can be invoked with no object instance whatsoever, how could there be a this reference?

The rule is that static methods (like the main() method) can never access instance methods or instance variables; static methods can invoke only other static class members directly. Another way to say this is that you cannot invoke an instance method or access an instance variable without an object instance.

pass by value

The truth is that everything—both objects and primitive types—is passed by value. For a primitive type, the value is whatever was assigned to the primitive before it was passed. For an object, the value is the actual object reference. All object references in the JVM are just 32-bit integers that the JVM maps to memory addresses.

switch statement

The switch statement can process only four primitive types: byte, short, char, and int. No other types are allowed for evaluation in a switch statement. Although char may not seem to be an integer, it is. The value it actually holds is the Unicode value, which is a 16-bit integer value. It is represented in code normally as an actual character, of course.

String Basics

String title = “Java”;
title = “Java Foundations”;

Remember, whenever Java “sees” a new string literal, it creates a new object. What is really happening in the previous two lines of code is as follows:
1. The variable title is declared a String.
2. The new String object “Java” is created in memory.
3. This new String object’s reference is stored in the title variable.
4. The new String object “Java Foundations” is created in memory.
5. The reference to this new String object is stored in the title variable.

Math Class

The Math class is final and all the methods defined in the Math class are static, which means you cannot inherit from the Math class and override these methods. Also, the Math class has a private constructor, so you cannot instantiate it.

Need of static in main

The static keyword is needed in the main () so that the interpreter can access the method right from the class instead of requiring an object. As you know of objects so far, you should know that normally a class is just a template for individual objects. A nonstatic method can be called only if an object has been created from a class. A static method can be called without any objects being created.

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.