Month: August 2015

Static Blocks in Java

Posted on Updated on

java-logo

In java you see “static variables”, “static methods”, “static classes” and “static blocks”. Static variables, static methods and static classes are known to everyone but what is this “static block”. Lets see what, where and how these static blocks are used.

But before going into “static block”, lets refresh what other static stuff are. Now “static variables” are class variables i.e., there will be only one copy for each class and not one copy for each object of the class and these variables will be accessed without instantiating the class. Then what are static methods. Again they are class methods i.e., they can be accessed without creating an instance of the class and like static variables, static methods will be accessed without instantiating the class. Note that static methods cannot access instance variables. They can access only static variables. Next what are static classes. You cannot declare a top-level class as a static class. Java will throw a compilation error. Only inner classes that are member classes can be declared as static. If we declare member classes as static, we can use it as a top-level class outside the context of top-level class. One catch here is “The static keyword does not do to a class declaration what it does to a variable or a method declaration.” – what it means is say for example you have a static variable, then to access that static variable you will use the notation
<<Class Name>>.<<Variable Name>>
but when you want to use the static inner class, you need to instantiate like
<<Top-level class name>>.<<Inner static class name>> newClass = new <<Top-level class name>>.<<Inner static class name>>();

Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code. And dont forget, this code will be executed when JVM loads the class. JVM combines all these blocks into one single static block and then executes. Here are a couple of points I like to mention:

  • If you have executable statements in the static block, JVM will automatically execute these statements when the class is loaded into JVM.
  • If you’re referring some static variables/methods from the static blocks, these statements will be executed after the class is loaded into JVM same as above i.e., now the static variables/methods referred and the static block both will be executed.

Lets see an example:


public class StaticExample{
    static {
        System.out.println("This is first static block");
    }

    public StaticExample(){
        System.out.println("This is constructor");
    }

    public static String staticString = "Static Variable";

    static {
        System.out.println("This is second static block and "
		                                        + staticString);
    }

    public static void main(String[] args){
        StaticExample statEx = new StaticExample();
        StaticExample.staticMethod2();
    }

    static {
        staticMethod();
        System.out.println("This is third static block");
    }

    public static void staticMethod() {
        System.out.println("This is static method");
    }

    public static void staticMethod2() {
        System.out.println("This is static method2");
    }
}

What will happen when you execute the above code? You will see below output.

This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2

Now lets the output. First all static blocks are positioned in the code and they are executed when the class is loaded into JVM. Since the static method staticMethod() is called inside third static block, its executed before calling the main method. But the staticMethod2() static method is executed after the class is instantiated because it is being called after the instantiation of the class.

Again if you miss to precede the block with “static” keyword, the block is called “constructor block” and will be executed when the class is instantiated. The constructor block will be copied into each constructor of the class. Say for example you have four parameterized constructors, then four copies of contructor blocks will be placed inside the constructor, one for each. Lets execute the below example and see the output.


public class ConstructorBlockExample{

    {
        System.out.println("This is first constructor block");
    }

    public ConstructorBlockExample(){
        System.out.println("This is no parameter constructor");
    }

    public ConstructorBlockExample(String param1){
        System.out.println("This is single parameter constructor");
    }

    public ConstructorBlockExample(String param1, String param2){
        System.out.println("This is two parameters constructor");
    }

    {
        System.out.println("This is second constructor block");
    }

    public static void main(String[] args){
        ConstructorBlockExample constrBlockEx = 
		             new ConstructorBlockExample();
        ConstructorBlockExample constrBlockEx1 = 
		             new ConstructorBlockExample("param1");
        ConstructorBlockExample constrBlockEx2 = 
		             new ConstructorBlockExample("param1", "param2");
    }
}

The output is :-

This is first constructor block
This is second constructor block
This is no parameter constructor
This is first constructor block
This is second constructor block
This is single parameter constructor
This is first constructor block
This is second constructor block
This is two parameters constructor

The above example is self-explanatory.
Now lets go back to static blocks.

There is an alternative to static blocks —you can write a private static method.


class PrivateStaticMethodExample {
    public static varType myVar = initializeClassVariable();
	
    private static varType initializeClassVariable() {
        //initialization code goes here
    }
}

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable. So, you kind of get more flexibility with a private static method in comparison to the corresponding static initialization block. This should not mislead that a ‘public’ static method can’t do the same. But, we are talking about a way of initializing a class variable and there is hardly any reason to make such a method ‘public’.

So what are the advantages of static blocks?

  • If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.
  • If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded.
  • Security related issues or logging related tasks

Ofcourse there are limitations for static blocks

  • There is a limitation of JVM that a static initializer block should not exceed 64K.
  • You cannot throw Checked Exceptions.
  • You cannot use this keyword since there is no instance.
  • You shouldn’t try to access super since there is no such a thing for static blocks.
  • You should not return anything from this block.
  • Static blocks make testing a nightmare.

Finally how to handle Exceptions in static blocks?
In methods, an exception can be handled by either passing through the Exception or handling it. But in a static block code, you cannot handle exceptions this way.

Generally a clean way to handle it is using a try-catch block but here since we dont have this option lets look at the available three options.

First: After logging the exception throw a RuntimeException which will end the current thread (unless caught by code instantiating / calling a static method on the class for the first time).

Second is calling System.exit(1) but this is not desirable in a managed environment like a servlet. This option is only for java applications and only if the static initializer block performs some critical (without which the program cannot be run successfully) function like loading the database driver.

Third and final option is to set a flag indicating failure. Later the constructors can check the flag and throw exceptions or retry in rare cases.

Finally, if the operation is not important to the functioning of the program then maybe a simple log entry is all that is required.

Advertisements

What are the difference between Delete,Truncate and Drop in SQL

Posted on Updated on

Again, it is another frequently asked question in SQL interview. Interviewer may ask this question different way and try to confuse you  but good knowledge always appreciated. Sometime interviewer only interest to know point to point answer but sometime  get to know some deep knowledge and asked a scenario base on given large data-set like performance and rollback table and etc.

Here, we will discuss about these aspect

Delete :-

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.

It is DML command and trigger does work on Delete operation

A rollback table will be created when this operation get performed.

Truncate :-

TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUCATE is faster and doesn’t use as much undo space as a DELETE.

It is DDL command and removes the record permanently.

To delete a large dataset is faster than Delete operation because it does not maintain temporary table like rollback table. Since rollback and undo does not supported.

Trigger does not get fired because trigger only work on DML ( Delete, Update and Select Operation ).

You cann’t use conditions(WHERE clause) in TRUNCATE.But in DELETE you can write conditions using WHERE clause

Drop :

The DROP command removes a table from the database. All the tables’ rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.

it is DDL command.

Trigger does not get fired because trigger only work on DML ( Delete, Update and Select Operation ).

You cann’t use conditions(WHERE clause) in TRUNCATE.But in DELETE you can write conditions using WHERE clause

 

TRUNCATE is much faster than DELETE.

When you type DELETE.all the data get copied into the Rollback Tablespace first.then delete operation get performed.Thats why when you type ROLLBACK after deleting a table ,you can get back the data(The system get it for you from the Rollback Tablespace).All this process take time.But when you type TRUNCATE,it removes data directly without copying it into the Rollback Tablespace.Thatswhy TRUNCATE is faster.Once you Truncate you cann’t get back the data.

Difference between WHERE vs HAVING clause in SQL

Posted on

This is most popular interview question that frequently asked in SQL and database interview. it’s very basic question that every programmer must know about SQL interview  likely Java,.Net and PHP programmer.

Where” clause is used for selection a row or set of rows from table, base on criteria like primary key or other column fields table rows get retrieved. It could be used in update, delete and select statement base on the criteria or more than one criteria.

Having” clause used on aggregate function that is work over Group by selection, Having clause always followed by Group by clause. It boost the better performance by avoiding unnecessary column sorting and grouping.

select max(state) from States having count(State) > 60

select employee, sum(bonus) from emp_bonus
group by employee having sum(bonus) > 1000;

Aggregate Function below :- 

  • AVG() – Returns the average value
  • COUNT() – Returns the number of rows
  • FIRST() – Returns the first value
  • LAST() – Returns the last value
  • MAX() – Returns the largest value
  • MIN() – Returns the smallest value
  • SUM() – Returns the sum

Difference between WHERE vs HAVING

  1. The WHERE clause specifies the criteria which individual records must meet to be selected by a query. It can be used without the GROUP BY clause. The HAVING clause cannot be used without the GROUP BY clause.
  2. The WHERE clause selects rows before grouping. The HAVING clause selects rows after grouping.
  3. The WHERE clause cannot contain aggregate functions. The HAVING clause can contain aggregate functions.

How to rounding-off numbers to a specified precision in xslt 1.0

Posted on Updated on

java-logoRecently we faced an issue to fixed round up a number upto specified precision number in xslt 1.0, there is no any function provided in this version to get resolved it. After a long dig and visited a tone of sites, finally we found the solution as given below :-

 

Rounding Numbers to a Specified Precision

Problem

You want to round to a specific number of decimal places; however, XSLT’s round, ceiling, and floorfunctions always map numbers to integer values.

Solution

XSLT 1.0

Multiply, round, and divide using a power of ten that determines how many decimal digits are required. Assuming $pi = 3.1415926535897932:

<xsl:value-of select="round($pi * 10000) div 10000"/>

 

results in 3.1416. Similarily:

<xsl:value-of select="ceiling($pi * 10000) div 10000"/>

 

results in 3.1416, and:

<xsl:value-of select="floor($pi * 10000) div 10000"/>

 

results in 3.1415.

Rounding to a specific number of decimal places is also achieved using format-number():

<xsl:value-of select="format-number($pi,'#.####')"/>

 

This results in 3.1416. This will work even if more than one significant digit is in the whole part because format-number never uses a format specification as an indication to remove significant digits from the whole part:

<xsl:value-of select="format-number($pi * 100,'#.####')"/>

 

This results in 314.1593.

You can use format-number to get the effect of truncating rather than rounding by using one more formatting digit than required and then chopping off the last character:

<xsl:variable name="pi-to-5-sig" select="format-number($pi,'#.#####')"/>
<xsl:value-of select="substring($pi-to-5-sig,1,string-length($pi-to-5-sig) -1)"/>

 

This results in 3.1415.

XSLT 2.0

The new XPath 2.0 round-half-to-even( ) function will do the trick for most applications. The half to even rule means that when the value being rounded is smack between the lower and higher values, then rounding will be in the direction that produces an even result. So round-half-to-even(1.115,2) eq 1.12 and round-half-to-even(1.125,2) eq 1.12 also! In the first case, we round up because 2 is even, and the second rounds down because 3 is not. The theory behind this is that if you have a bunch of numbers, you should roughly round up as often as you round down so rounding errors cancel out. As you probably guessed, the second argument is the number of decimal places to round to.

If your application mandates that 5 in the last decimal place always rounds upward, you can use the techniques employed in the XSLT 1.0 recipe.

Discussion

The multiply, round, and divide technique works well as long as the numbers involved remain within the representational limits of IEEE floating point. If you try to capture too many places after the decimal, then the rules of IEEE floating point will interfere with the expected result. For example, trying to pick up 16 decimal digits of pi will give you only 15:

<xsl:value-of select="round($pi * 10000000000000000) div 10000000000000000"/>

 

This results in 3.141592653589793, not 3.1415926535897932.

An alternative technique manipulates the number as a string and truncates:

<xsl:value-of select="concat(substring-before($pi,'.'), '.',  substring(substring-after($pi,'.'),1,4))"/>

 

and results in 3.1415.

The effect of ceiling or round can be obtained by this technique at the cost of additional complexity:


<xsl:variable name="whole" select="substring-before($pi,'.')"/> 
<xsl:variable name="frac" select="substring-after($pi,'.')"/>
<xsl:value-of select="concat($whole, '.',  substring($frac,1,3), round(substring($frac,4,2) div 10))"/>

 

This results in 3.1416.

ref link :-
http://flylib.com/books/en/2.765.1.41/1/