Tuesday, 3 July 2012

How static block works in Java


Static block and its description in Java

Static Block in Java:

In java, static is a keyword. All static stuffs(static variable, static method) belong to the class and not to the object(instance). Before going to static block, let's discuss about some static stuffs.


Static variables are basically class variables. When you define a static variable for your class implementation, there will be only one copy of the variable for the class rather than one for each instance of the class. They can be accessed without creating an instance of the class.

Static methods also called class methods and can be accessed without creating an instance of the class and like static variables, static methods will be accessed without instantiating the class .

Ex:
public class Test
    {
    static int foo = 12345;        
     static void TestMethod()
                {
               foo++;
                        }
 public static void main(String arge[])
 {
 System.out.println(foo);          //directly accessed  o/p:12345
 TestMethod();                    // directly accessed
 System.out.println(foo);        // o/p : 12346
 }
    
    }

Static blocks:

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

    static {          // whatever code is needed for initialization goes here        }
  3. A class can have more then one static block in the class body.The run time system guarantees that static initialization blocks are called in the order that they appear in the source code.
  4. 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.

Ex:
public class Test
{
static int num;
static int res;
     static
            {
             num = 10;
             res = 12;
             System.out.println("I am static block, I am called first.");
             System.out.println("Result : "+(num*res));                              // o/p : 120
             past();                                                                                   // o/p : Method Block
     }
public static void main(String args[])
          {
          System.out.println("I am main() method, executed after static block.");
          System.out.println("Result : "+(num*res)); // o/p : 120
          }
static void past()
          {
          System.out.println("Method Block");
         }
}


O/P:

I am static block, I am called first.
Result : 120
Method Block
I am main() method, executed after static block.
Result : 120

 5. Static block can access instance variables (non-static variables) and instance methods by         creating an object of the class.

Ex :
public class Test
{
int num;
int res;
static Test T1;
    static
          {
          T1=new Test();
          T1.num = 10;
          T1.res = 12;
          System.out.println("I am static block, I am called first.");
          System.out.println("Result : "+(T1.num*T1.res));                      // o/p : 120
          T1.past();                          // call to concrete method ,   o/p : Method Block
  }

public static void main(String args[])
{
System.out.println("I am main() method, executed after static block.");
}
void past()
    {
     System.out.println("Method Block");
    }
}


O/p :
I am static block, I am called first.
Result : 120
Method Block
I am main() method, executed after static block.

Advantages of static blocks

  • If you’re loading drivers and other items into the namespace. (for instance Class.forName(”org.h2.Driver”)).
  • Initialize your static members at once ,as static block run once in the program execution.
  • Limitations for static blocks
  • You cannot throw Checked Exceptions.
  • “this” keyword can not be used 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.


Non-Static Block/ constructor block

  • if we remove static keyword from static block/ initialization block, then it said to be non-Static block / constructor block.
  • This block is executed when the class is instantiated.
  • How many time your class get instantiated, constructor block/ non-Static block will called each time. That means constructor block will be copied into each constructor of the class.


Here is an Example :

public class NonStaticBlock{
{
System.out.println("First Non Static block");
}

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

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

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

{
System.out.println("Second Non Static block");
}

public static void main(String[] args){
NonStaticBlock nonStaticEx = new NonStaticBlock();
NonStaticBlock nonStaticEx1 = new NonStaticBlock("java");
NonStaticBlock nonStaticEx2 = new NonStaticBlock("java", "oracle");
}
}

O/P will be like this:
First Non Static block                                 // coming from first constructor block
Second Non Static block                          // coming from second constructor block
This is no parameter constructor              // First instance created & constructor called
First Non Static block
Second Non Static block
This is single parameter constructor
First Non Static block
Second Non Static block
This is two parameters constructor

Wednesday, 13 June 2012

Spring default included JAR Files and their short descriptions

spring-aop.jar
To Implement Spring's AOP feature, this jar is used. You also need to include this JAR in your application if you plan to use other features in Spring that use AOP, such as declarative transaction management.
spring-beans.jar
This jar contains all of Spring’s dependency injection ,contains the bean factories and supporting classes.
spring-context.jar
To build the Spring application context, this jar is used. it packages the main ApplicationConext interface and its implementations together with code for instrumentation, JNDI, scheduling, themes, and validation.
spring-context-support.jar
This package contains utility Spring code—this means caching, instrumentation, e-mail and scheduling support, and the very interesting scripting languages support.
spring-core.jar
This contains the core files of the Spring Framework: it deals with annotations, enumerations, task execution, resource loading, and other utilities and exceptions you may find useful even outside the context of the Spring Framework.
spring-jdbc.jar
This package contains code for the JDBC support classes, namely the JdbcTemplate and JdbcDaoSupport classes.
spring-jms.jar
This JAR contains code for JMS.
spring-orm.jar
This archive contains the files needed for object-relational mapping(ORM) tools. Including this package on your classpath will give you Spring support for Hibernate 3, iBATIS, JDO, JPA, and TopLink.
spring-test.jar
This package contains support code to write unit and integration tests using the Spring Framework. It supports the JUnit 3, JUnit 4, and TestNG testing frameworks. In addition, you can use classes from the org.springframework.mock package, which represent
mock implementations of JNDI and web classes.
spring-tx.jar
This one contains support for core data access exceptions and transaction technologies. These two areas are closely bound together, because the transactions generally work with some data access code.
spring-web.jar
This JAR contains code for the Spring web application support (utilities, binders, multipart resolvers).
spring-webmvc-portlet.jar
This JAR contains code needed to build portlet-based (rather than servlet-based) web applications. If you have an application server
that supports the Portlet API (JSR 168), you can use this package.
spring-webmvc-struts.jar
This package contains code needed to use Spring with the Jakarta Struts Framework.
spring-webmvc.jar
This package contains the Spring MVC code.

Tuesday, 17 April 2012

Few OCJP/SCJP Questions and Answers


1. public class LocalTime {
public static void main(String [] args) {
int second;
int min; // second & min only declared but not initialized
System.out.println("Welcome");
second = 180; // Initialize the variable
System.out.println("Minute " + min);
}
}

Ans : Code fails in compilation .Local variable should be initialize before they used in the method/block. Here “min” variable is no where used in the program..

2. public class LocalTest {
public static void main(String [] args) {
int a;
if (args[0] != null) { // assume you know this will
// always be true

a = 7; // compiler can't tell that this
//  statement will run
}
int b = a; //Compiler will choke here
}
}
Ans: Compilation Error. The variable “a” is only initialize in the loop. When JVM comes from the loop, it can not find the value of “a” .

3. class Foo {
static int size = 7;
static void changeIt(int size) {
size = size + 100;
System.out.println("size in changeIt is " + size);
}
public static void main (String [] args) {
Foo f = new Foo();
System.out.println("size = " + size);
changeIt(size);
System.out.println("size after changeIt is " + size);
}
}
o/p :
size = 7
size in changeIt is 107
size after changeIt is 7

4. class TestWrapper {
public static void main(String args[]) {
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");
}
}

o/p:
different objects
meaningfully equal

5 .
class TestWrapper {
public static void main(String args[]) {
Integer i2 = 20;
Integer i3 = 20;
if(i2 == i3) System.out.println("same object");
if(i2.equals(i3)) System.out.println("meaningfully equal");
}
}

o/p :
same object
meaningfully equal

NB :For Short & Integer range from -128 to 127. When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.

6. class Boxing {
static Integer x;
public static void main(String [] args) {
doStuff(x);
}
static void doStuff(int z) {
int z2 = 5;
System.out.println(z2 + z);
} }

0/p: It will throw NullPointerException at Runtime bacause when JVM tries to invoke dostuff(x) method, x does not have the value to outbox.

NB : wrapper reference variables can be null. You have to take care for code that appears to be doing safe primitive operations, but that could throw a NullPointerException:


7. class LongTest {
static void go(int x) { System.out.print("int "); }
static void go(long x) { System.out.print("long "); }
static void go(double x) { System.out.print("double "); }
public static void main(String [] args) {
byte b = 5;
short s = 5;
long l = 5;
float f = 5.0f;
go(b);
go(s);
go(l);
go(f);
}
}
Which produces the output:
int int long double

8. class Dog {
public static void main(String [] args) {
Dog d = new Dog();
d.test(new Long(5)); // can't widen an Integer
// to a Long
}
void test(Double x) { }
}


O/P :  Compilation Fails.
Wrapper class can not widen with one another.



9. class TryWiden {
static void go(Object o) {
Integer b2 = (Integer) o; // ok - it's a Integer object
System.out.println(b2);
}
public static void main(String [] args) {
Integer b = 10;
go(b); // can this integer turn into an Object ?
}
}

o/p: 10

Since Object is the parent class of all wrapper classes(here Byte),so it can widen to Object.

10.
class MixerTest {
MixerTest() { }
MixerTest( MixerTest m) { m1 = m; }
MixerTest m1;
public static void main(String[] args) {
MixerTest m2 = new MixerTest();
MixerTest m3 = new MixerTest(m2); m3.go();
MixerTest m4 = m3.m1; m4.go();
MixerTest m5 = m2.m1; m5.go();
}
void go() { System.out.print("hi "); }
}

what will be the o/p ?

o/p : hi hi, followed by an exception
Because m2 object’s m1 instance variable is never initialized, so when m5 tries to use it a NullPointerException is thrown


11. class Bird {
{ System.out.print("b1 "); }
public Bird() { System.out.print("b2 "); }
}
class Raptor extends Bird {
static { System.out.print("r1 "); }
public Raptor() { System.out.print("r2 "); }
{ System.out.print("r3 "); }
static { System.out.print("r4 "); }
}
class Hawk extends Raptor {
public static void main(String[] args) {
System.out.print("pre ");
new Hawk();
System.out.println("hawk ");
}
}

o/p : r1 r4 pre b1 b2 r3 r2 hawk
Static init blocks are executed at class loading time, instance init blocks run
right after the call to super() in a constructor. When multiple init blocks of a single type occur in a class, they run in order, from the top down

12. public class Make {
static int make = 7;
public static void main(String[] args) {
new Make().go(make);
System.out.print(" " + make);
}
void go(int make) {
make++;
for(int make = 3; ouch < 6; ouch++)
;
System.out.print(" " + make);
}
}

o/p : Compilation fails because the variable “make” is declare again in for loop

13. class Dozens {
int[] dz = {1,2,3,4,5,6,7,8,9,10,11,12};
}
public class Mango{
public static void main(String[] args) {
Dozens [] da = new Dozens[3];
da[0] = new Dozens();
Dozens d = new Dozens();
da[1] = d;
d = null;
da[1] = null;
// do stuff
}
}

question : How many objects this program will create & how many are eligible for garbage collection ?

Ans : 5 objects are created & 2 objects are eligible for Garbage Collection

Monday, 16 April 2012

Explicitly Make Objects Eligible for Garbage Collection



As all java people know how Memory Management & Garbage Collection work in java.
As of Summary: Garbage collector revolves around making sure that the heap has as
much free space as possible. Objects are created in the heap. When JVM(Java Virtual Machine) senses that memory is running low, at that time it calls garbage collector to remove/delete the unused objects that are not needed any more from memory(heap)...

Explicitly Makes Objects Eligible for Collection

(a). Nulling a Reference:
  1. An object becomes eligible for garbage collection when there are no more reachable references to it. To remove a reference to an object is to set the reference variable that refers to the object to null.

Program code :

public class RemoveReference {
public static void main(String [] args) {

StringBuffer sb = new StringBuffer("Reference");

System.out.println(sb); 
// Here the StringBuffer object is not eligible for collection

sb = null;
// Now the StringBuffer object is eligible for collection
}
}

(b). Reassigning a Reference Variable:

  1. We can also decouple a reference variable from an object by setting the reference variable to refer to another object.
  1. The objects created in the method are eligible for garbage collection ,once the method has returned.
  2. If an object is returned from the method, its reference might be assigned to a reference variable in the method that called it; hence, it will not be eligible for collection

Program Code:

import java.util.Date;
class ReassignReference {
public static void main(String [] args) {
Date d = getDate(); // Reference return from the method

StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("goodbye");

System.out.println(s1);
// At this point the StringBuffer "hello" is not eligible

s1 = s2; // Redirects s1 to refer to the "goodbye" object
// Now the StringBuffer "hello" is eligible for collection

}
public static Date getDate() {
Date d2 = new Date();

StringBuffer now = new StringBuffer(d2.toString());
// object eligible to garbage collector even we don't set the object as null explicitly.

System.out.println(now);

return d2; // Reference Return , not eligible for garbage collector
}
}

(c) .Isolating a Reference

1.There is another way in which objects can become eligible for garbage collection,even if they still have valid references! We call this scenario "islands of isolation."

Program Code :

public class Island {
Island i;
public static void main(String [] args) {
Island i2 = new Island();
Island i3 = new Island();
Island i4 = new Island();

i2.i = i3; // i2 refers to i3
i3.i = i4; // i3 refers to i4
i4.i = i2; // i4 refers to i2

i2 = null;
i3 = null;
i4 = null;
// do complicated, memory intensive stuff
}

}


When the code reaches // do complicated, the three Island objects (previously known as i2, i3, and i4) have instance variables so that they refer to each other, but their links to the outside world (i2, i3, and i4) have been null. These three objects are eligible for garbage collection.

(d) Forcing Garbage Collection

  1. Garbage collection cannot be forced by a programmer.
  2. However, Java provides some methods that allow you to request that the JVM perform garbage collection.
  3. We can call garbage collector using Runtime java classes.
Ex: Runtime.getRuntime().gc();
Ex: System.gc();