Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Friday, November 14, 2008

Final, Finally and Finalize

Here I would like to discuss about some Keywords of Core Java. Here I am going to give you the basic idea about these keywords. This question is frequently asked in the interviews in the earlier stage of Career. Ok let's get into the business.

Final : Final is a keyword can be used in 3 scenarios. Firstly declare a class as Final as given below.

"public final class Test " If you declare a class like this that means you can not extend this class. That means "public class TestTwo extends Test" will NOT compile.
Second, You can declare method as final. If you declare a method final, you can't override the Final method in your subclasses. what if you do overload the final method. Yes, you can over load the final method.
Lastly, if the Final variable is declared you can not change the value of this. This indirectly means once you assign the value to any Final variable you can not change or modify the value of it. Generally these final variables are used while declaring constants with the combination of Static, Eg : PI value.

Finally : Finally is a block used in Exception handling. We all know about try and catch blocks where we put the statements where error could occur in try block and and we catch the exceptions in the catch block by passing the Exception object as argument. after all catch blocks you can put this Finally block. This will be executed in either case of exception. So, you can put the mandatory closing statements of files or connections you opened in the beginning.

Finalize() : Finalize is a method of class java.lang.object. This has to be overridden in the class you want according to your requirement. This method will be executed before the object get garbage collected. So, this would be executed when there will be no reference remain for the object.
protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}

Saturday, October 18, 2008

Read Only

Read Only

We often get in trouble with small problems like making the things read only.
This is very useful to restrict the concurrency issues it could be a request or a result set or a data entry like HTML.
Even some times we want to make the files read only too on the fly.

This sample code makes a file read only.

import java.io.File;

public class ReadOnlyExp {
public static void main(String[] args) {
File file=new File("c:\\MyFile");
file.setReadOnly();
}
}

How to make the HTML element read only.

READONLY = true;


You can also use DISABLED=”true” for any HTML Element.



Hope this was useful.