Friday 20 July 2012

string


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 import


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

extends vs runnable


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.