Archive for the ‘Java’ Category

extends vs runnable

Posted: July 20, 2012 in Java

Extend vs Runnable

     class     Extends   Thread

class Myclass Extends Thread

class Implements Runnable

class Myclass implements Runnable

Thread is class

Thread is a class that’s why

We have to use extends key word

Runnable is an interface

Runnable is an interface so we hv

use implements key word

Does not support the mltiinheritence

If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature

class Mine extends Thread,HttpServlet

  Not possible in java

support the mltiinheritence

If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems

class Mine implements Runnable

,Serializable extends HttpServlet

 

 Does not override the run() method to start() the thread. No compile and run time exceptions.

class Mine extends Thread{

public static void main(){

new Mine().start();

}

}

 should override (implements) the run() method otherwise it gives compile time error

class Mine implements Runnable{

public void run(){

System.out.println(“run”);

}

public static void main(){                                           Thread t = new Thread(new Mine());                                           t.start();

}

 

  each of your thread creates unique object and associate with it. (plz go through the below example to know the difference)  it shares the same object to multiple threads

(plz go through the below example to know the difference)

 

class ImplementsRunnable implements Runnable {

private int counter = 0;

public void run() {

counter++;

System.out.println(“ImplementsRunnable : Counter : ” + counter);

}

}

class ExtendsThread extends Thread {

private int counter = 0;

public void run() {

counter++;

System.out.println(“ExtendsThread : Counter : ” + counter);

}

}

public class ThreadVsRunnable {

public static void main(String args[]) throws Exception {

//Multiple threads share the same object.

ImplementsRunnable rc = new ImplementsRunnable();

Thread t1 = new Thread(rc);

t1.start();

Thread.sleep(1000); // Waiting for 1 second before starting next thread

Thread t2 = new Thread(rc);

t2.start();

Thread.sleep(1000); // Waiting for 1 second before starting next thread

Thread t3 = new Thread(rc);

t3.start();

//Creating new instance for every thread access.

ExtendsThread tc1 = new ExtendsThread();

tc1.start();

Thread.sleep(1000); // Waiting for 1 second before starting next thread

ExtendsThread tc2 = new ExtendsThread();

tc2.start();

Thread.sleep(1000); // Waiting for 1 second before starting next thread

ExtendsThread tc3 = new ExtendsThread();

tc3.start();

}

}

Output:

ImplementsRunnable : Counter : 1

ImplementsRunnable : Counter : 2

ImplementsRunnable : Counter : 3

ExtendsThread : Counter : 1

ExtendsThread : Counter : 1

ExtendsThread : Counter : 1

If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems

each of your thread creates unique object and associate with it.

In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.

Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.

When to use Runnable?

Use Runnable interface when you want to access the same resource from the group of threads. Avoid using Thread class here, because multiple objects creation consumes more memory and it becomes a big performance overhead.

Apart from this, object oriented designs have some guidelines for better coding.

 

Coding to an interface rather than to implementation. This makes your software/application easier to extend. In other words, your code will work with all the interface’s subclasses, even ones that have not been created yet.

Interface inheritance (implements) is preferable – This makes your code is loosely coupling between classes/objects.(Note : Thread class internally implements the Runnable interface)

Example: coding to an interface.

Map subject = new HashMap();

Assigning HashMap object to interface Map,  suppose in future if you want to change HashMap to Hashtable or LinkedHashMap you can simple change in the declaration part is enough rather than to all the usage places. This point has been elaborately explained here.

Which one is best to use?

Ans : Very simple, based on your application requirements you will use this appropriately. But I would suggest, try to use interface inheritance i.e., implements Runnable.

 

Advertisements

static import

Posted: July 20, 2012 in Java

Static Import is a new feature added in Java 5 specification. Java 5 has been around the corner for some time now, still lot of people who are new in Java world doesn’t know about this feature.

Although I have not used this feature in my work, still it is interesting to know about.

What is Static Import?

In order to access static members, it is necessary to qualify references with the class they came from. For example, one must say:

double r = Math.cos(Math.PI * theta);

or

System.out.println(“Blah blah blah”);

 

You may want to avoid unnecessary use of static class members like Math. and System. For this use static import. For example above code when changed using static import is changed to:

import static java.lang.System.out;

import static java.lang.Math.PI;

import static java.lang.Math.cos;

double r = cos(PI * theta);

out.println(“Blah blah blah”);

So whats the advantage of using above technique? Only advantage that I see is readability of the code. Instead of writing name of static class, one can directly write the method or member variable name.

Also keep one thing in mind here. Ambiguous static import is not allowed. i.e. if you have imported java.lang.Math.PI and you want to import mypackage.Someclass.PI, the compiler will throw an error. Thus you can import only one member PI.

A static import declaration has two forms—one that imports a particular static member (which is known as singlestatic import) and one that imports all static members of a class (which is known as static import on demand). The following syntax imports a particular static member:

import static packageName.ClassName.staticMemberName;

where packageName is the package of the class (e.g., java.lang), ClassName is the name of the class (e.g., Math) andstaticMemberName is the name of the static field or method (e.g., PI or abs). The following syntax imports all static members of a class:

import static packageName.ClassName.*;

where packageName is the package of the class (e.g., java.lang) and ClassName is the name of the class (e.g., Math). The asterisk (*) indicates that all static members of the specified class should be available for use in the class(es) declared in the file. Note that static import declarations import only static class members. Regular import statements should be used to specify the classes used in a program.

 

In order to use the static import flavor of java. We have to declare all the variables and methods as static and public for availability and accessing methods and variables using Class name. its better to call it import static to avoid syntactical errors. See the examples below.

package aaa.bbb.ccc;

public class sss {

public static final String xxx=”hello”;

public static int mone(){

return 10;

}

}

 

package ccc.bbb.aaa;

import static aaa.bbb.ccc.sss.*;

import static java.lang.System.out;

public class Example {

public static void main(String[] args) {

out.println(xxx);

out.println(mone());

}

}

Output:

hello

10

String

Posted: June 20, 2012 in Java

String is immutable:

String s1 = gopal;

String s2= Krishna;

s1 = s1+s2;

System.out.println(s1);

Output:

gopalkrishna

the output of the program “gopalakrishna” . it seems that the string s1 content is modified. Earlier s1 got “gopal” and s2 had “Krishna”. After s1+s2, they are joined and total string become “gopalakrishna”. This string is assigned to s1 again. If s1 is mutable, it gets new string “gopalakrishna”. This is what we can see in the output. So s1 appear to be mutable. But we learned that strings are immutable.

s1 is definitely immutable. But why the output of the program like that? In the program, jvm creates two objects, s1 and s2 seperately, as shown in the below figure. When s1+s2 is done, jvm creates new object and stores the new object and stores the string “gopalakrishna” in that object. But it doesn’t modify the contents of the string s1. After creating new object, the reference “s1” is adjusted to refer to that new object. The point we should observe here is that the contents of the string s1 are not modified. This is the reason string objects are immutable. The old object that contains “gopal” has lost its reference. So it is called “unreferenced object” and garbage collector will remove it from memory.

static vs dynamic

Posted: June 20, 2012 in Java

Static Vs Dynamic binding

Static Polymorphism:

The Polymorphism exhibited at compile time is called static polymorphism. Here Java Compiler knows without any ambiguity which method is called at the time of compilation. Of Course, JVM executes the method later, but the compiler knows and can bind the method call with method code(body) at the time of compilation. So, it is called ‘static binding’ or ‘compile time polymorphism’.

Static methods, private methods, and final methods and variables are examples for static polymorphism. The reason is that all of those methods maintain single copy in memory that is available to the objects of the class. So the java compiler knows which method is called at the time of compilation and it needs not wait till the objects are created.

class One{

static void calculate(double x)

{

System.out.println(“Square Value   “+(x*x));

}

}

class Two extends One{

static void calculate(double x)

{                              System.out.println(“Square Root   “+Math.sqrt(x));

}

}

 

public class StaticPoly {

public static void main(String[] args) {

One o = new Two();

o.calculate(25);

}

}

Output :

Square Value   625.0

Dynamic Polymorphism:

The Polymorphism exhibited at runtime is called dynamic polymorphism. This means when a method is called, the method call bound to the method body at the time of running the program, dynamically. In this case, java compiler does not which method is called at the time of compilation. Only JVM knows at runtime which method is to be executed.

class One{

void calculate(double x)

{

System.out.println(“Square Value   “+(x*x));

}

}

class Two extends One{

void calculate(double x)

{

System.out.println(“Square Root   “+Math.sqrt(x));

}

}

 

public class DynamicPoly {

public static void main(String[] args) {

One o = new Two();

o.calculate(25);

}

}

 

output:  

Square Root   5.0

Who will decide which method is to be executed? Is it java compiler or JVM?

Methods are called by using an object, the java compiler can not decide at the time of compilation which method is actually called by user. It has to wait till the object is created for class. And creation objects take place at runtime by jvm. Now jvm should decide which method is actually called by user at runtime(dynamically).


IllegalStateException

It is child class of Runtime Exception and its is unchecked. It is raised programmatically when ever a method has invoked at illegal or in appropriate time.

Example 1:

After invalidating a session we are not allowed to call getId() method, violation leads to  illegalThreadStateException.

session.invalidate();

session.getId(1);

output:

Exception in thread “main” java.lang.IllegalStateException


IllegalThreadStateException

It is child class of Runtime Exception and its is unchecked. It is raised programmatically when ever a method has invoked at illegal or in appropriate time.

Example 1:

After Starting a Thread we are not allowed to start the same thread again violation leads to illegalThreadStateException

public class Test extends Thread

{

public void run(){

System.out.println(“I am from run “);

}

public static void main(String[] args) {

Test test1 = new Test();

Thread thread = new Thread(test1);

thread.start();

thread.start();

}            }

output:

I am from run Exception in thread “main”
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:595)
at com.clarity.test1.main(test1.java:108)

 


Number Format Exception

 It is child class of illegalArgumentException and it is unchecked.

It is thrown programmatically to indicate that the application has attempted to convert a string to number but the string is not format properly

Example:

public static void main(String[] args) {

      Integer integer = new Integer(“10”);

      System.out.println(integer);

      Integer integer2 = new Integer(“ten”); —–> string to number but the string is  not format properly.                     

      System.out.println(integer2);

            }}

Output:

10

Exception in thread “main” java.lang.NumberFormatException: For input string: “ten”

      at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)

      at java.lang.Integer.parseInt(Integer.java:447)

      at java.lang.Integer.<init>(Integer.java:620)

            at com.clarity.test1.main(test1.java:97)