Friday 30 May 2014

Initialization of Fields in Interfaces

Every declarator in a field declaration of an interface must have a variable initializer, or a compile-time error occurs.

The initializer need not be a constant expression. It is a compile-time error if the initializer of an interface field uses the simple name of the same field or another field whose declaration occurs textually later in the same interface.

It is a compile-time error if the keyword this or the keyword super  occurs in the initializer of an interface field, unless the occurrence is within the body of an anonymous class. At run time, the initializer is evaluated and the field assignment performed exactly once, when the interface is initialized.

Note that interface fields that are constant variables  are initialized before other interface fields. This also applies to static fields that are constant variables in classes . Such fields will never be observed to have their default initial values , even by devious programs.

Example : Forward Reference to a Field
interface Test {
    float f = j;
     int j = 1;
     int k = k + 1;
}

This program causes two compile-time errors, because j is referred to in the initialization of f before j is declared, and because the initialization of k refers to k itself.

Ambiguous Inherited Fields With Interface

If two fields with the same name are inherited by an interface because, for example, two of its direct superinterfaces declare fields with that name, then a single ambiguous member results. Any use of this ambiguous member will result in a compile-time error. In the program:

interface BaseColors {
     int RED = 1, GREEN = 2, BLUE = 4;
}
interface RainbowColors extends BaseColors {
    int YELLOW = 3, ORANGE = 5, INDIGO = 6, VIOLET = 7;
}
interface PrintColors extends BaseColors {
     int YELLOW = 8, CYAN = 16, MAGENTA = 32;
}
interface LotsOfColors extends RainbowColors, PrintColors {
     int FUCHSIA = 17, VERMILION = 43, CHARTREUSE = RED+90;
}
public class Test implements LotsOfColors {
    public static void main()
   {
       System.out.println(YELLOW); // OOPSS..!!....Got Error here
       System.out.println(RED); // Shock....!!....Run Successfully...
   }
}

the interface LotsOfColors inherits two fields named YELLOW. This is all right as long as the interface does not contain any reference by simple name to the field YELLOW. (Such a reference could occur within a variable initializer for a field.)

Even if interface PrintColors were to give the value 3 to YELLOW rather than the value 8, a reference to field YELLOW within interface LotsOfColors would still be considered ambiguous.

For RED Shock :: Why Run Successfully...

If a single field is inherited multiple times from the same interface because, for example, both this interface and one of this interface's direct superinterfaces extend the interface that declares the field, then only a single member results. This situation does not in itself cause a compile-time error.

In the previous example, the fields RED, GREEN, and BLUE are inherited by interface LotsOfColors in more than one way, through interface RainbowColors and also through interface PrintColors, but the reference to field RED in interface LotsOfColors is not considered ambiguous because only one actual declaration of the field RED is involved.

Tuesday 27 May 2014

Why the return value is 0 instead of 100?

public class FinallyReturnVariableAlter
{
   public static void main(String[] args)
  {
     System.out.println(test());
  }

  public static int test()
 {
    int i=0;
    try
   {
      return i;
   }
   finally
  {
    i+=100;
  }
  }
}

 Answer By Lokesh Gupta :
  • Every function call in java leads to creation of extra memory space created where return value is stored for reference after function execution completes and execution return to caller function back.
  • At that time, that special memory address where return value is stored, if referenced back as return value of function.
  • Here, trick is, the memory slot store the value of returned value, not its reference. So, once any return statement is encountered its value is copied in memory slot. That’s why if you change the value of “i” in finally, return value does not change because its already copied to memory slot.
  • We any other return statement is encountered (e.g. in finally block), its value will be overwritten again. So, it you want to return 100, use return statement in finally also.;

Monday 26 May 2014

Java tricks. Extending enumerations

Goal: 1) to have a type that represents a static set of constant values, so we can benefit from the compile-time check… or in less words, an Enum type, 2) to be able to extend the pre-defined set of values in the client class that extends a base client class… ideally, NewEnum extends BaseEnum.
Unfortunately, it’s not possible to extend enum type in Java, because of the enum nature: enum is an ordinal type, which makes it possible to be used in switch operator.
So the solution I’ve come up with is to introduce an interface. Let’s see how it works with the following example.
public interface State {
    String name(); // will be implemeted by java.lang.Enum class
}public class Entity {
    private State state = ObjectState.CREATED;
    public void setState(State state) { this.state = state; }
    public State getState() { return state; }
    public enum ObjectState implements State {
        CREATED, ACTIVE, DELETED
    }
}
public class Order extends Entity {
    public enum OrderState implements State {
        ACCEPTED, DELIVERED, CANCELLED
    }
}
public class EntityController {
    public void create(Entity entity) { entity.setState(ObjectState.CREATED); }
    public void delete(Entity entity) { entity.setState(ObjectState.DELETED); }
    public void activate(Entity entity) { entity.setState(ObjectState.ACTIVE); }
}
public class OrderController extends EntityController {
    public void accept(Order order) { order.setState(OrderState.ACCEPTED); }
    public void deliver(Order order) { order.setState(OrderState.DELIVERED); }
    public void cancel(Order order) { order.setState(OrderState.CANCELLED); }
}
Pros: both goals achieved, namely we’ve got static constant values and we are not limited by a pre-defined set of values, we can extend it for future use cases.
Cons: there’s no real extensibility of base enum, so we should be aware of the existing base enum before ‘extending’ it, so we don’t repeat values from it.

Why is super.super.method(); not allowed in Java? (Child To Grandfather...LOL)


I have 3 classes they inherit from each other as follows:
A

B

C
Inside each class I have the following method:
protected void foo() {
...
}
Inside class C I want to call foo from class A without calling foo in B:
protected void foo() {
// This doesn't work, I get the following compile time error:
// Constructor call must be the first statement in a constructor
super().super().foo();
}

It violates encapsulation. You shouldn't be able to bypass the parent class's behaviour. It makes sense to sometimes be able to bypass your own class's behaviour (particularly from within the same method) but not your parent's. For example, suppose we have a base "collection of items", a subclass representing "a collection of red items" and a subclass of that representing "a collection of big red items". It makes sense to have:
public class Items
{
public void add(Item item) { ... }
}

public class RedItems extends Items
{
@Override
public void add(Item item)
{
if (!item.isRed())
{
throw new NotRedItemException();
}
super.add(item);
}
}

public class BigRedItems extends RedItems
{
@Override
public void add(Item item)
{
if (!item.isBig())
{
throw new NotBigItemException();
}
super.add(item);
}
}
That's fine - RedItems can always be confident that the items it contains are all red. Now suppose we were able to call super.super.add():
public class NaughtyItems extends RedItems
{
@Override
public void add(Item item)
{
// I don't care if it's red or not. Take that, RedItems!
super.super.add(item);
}
}
Now we could add whatever we like, and the invariant in RedItems is broken.
Does that make sense?


You can't even use reflection. Something like

Class superSuperClass = this.getClass().getSuperclass().getSuperclass();
superSuperClass
.getMethod("foo").invoke(this);
 
would lead to an InvocationTargetException, because even if you call the foo-Method on the superSuperClass, it will still use C.foo() when you specify "this" in invoke. This is a consequence from the fact that all Java methods are virtual methods.

Finally we have only one way: Child To Papa... And Papa To Grand Papa... 

Saturday 24 May 2014

When should we implement Serializable interface?

  1. From What's this "serialization" thing all about?:
    It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s).
    The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
    Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
    So, implement the Serializable interface when you need to store a copy of the object, send them it to another process on the same system or over the network.
  2. Because you want to store or send an object.
  3. It makes storing and sending objects easy. It has nothing to do with security.

Friday 23 May 2014

Static synchronization

Today my mood is to play with thread...let's start:
If you make any static method as synchronized, the lock will be on the class not on object.
static synchronization

Problem without static synchronization

Suppose there are two objects of a shared class(e.g. Table) named object1 and object2.In case of synchronized method and synchronized block there cannot be interference between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that have a single lock.But there can be interference between t1 and t3 or t2 and t4 because t1 acquires another lock and t3 acquires another lock.I want no interference between t1 and t3 or t2 and t4.Static synchronization solves this problem.

Example of static synchronization

In this example we are applying synchronized keyword on the static method to perform static synchronization.
  1. class Table{  
  2.   
  3.  synchronized static void printTable(int n){  
  4.    for(int i=1;i<=10;i++){  
  5.      System.out.println(n*i);  
  6.      try{  
  7.        Thread.sleep(400);  
  8.      }catch(Exception e){}  
  9.    }  
  10.  }  
  11. }  
  12.   
  13. class MyThread1 extends Thread{  
  14. public void run(){  
  15. Table.printTable(1);  
  16. }  
  17. }  
  18.   
  19. class MyThread2 extends Thread{  
  20. public void run(){  
  21. Table.printTable(10);  
  22. }  
  23. }  
  24.   
  25. class MyThread3 extends Thread{  
  26. public void run(){  
  27. Table.printTable(100);  
  28. }  
  29. }  
  30.   
  31.   
  32.   
  33.   
  34. class MyThread4 extends Thread{  
  35. public void run(){  
  36. Table.printTable(1000);  
  37. }  
  38. }  
  39.   
  40. class Use{  
  41. public static void main(String t[]){  
  42. MyThread1 t1=new MyThread1();  
  43. MyThread2 t2=new MyThread2();  
  44. MyThread3 t3=new MyThread3();  
  45. MyThread4 t4=new MyThread4();  
  46. t1.start();  
  47. t2.start();  
  48. t3.start();  
  49. t4.start();  
  50. }  
  51. }  
Output:1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

Thursday 22 May 2014

Java's return value in try-catch-finally mechanism

Hello friends again question with try,catch and finally..i like it ...lol..

Here sample code is :

public class J2 extends J1 {

    public static int function() {
        try {
            return 1; // We think after return function complete here ...?
        } catch (Exception e) {
            return 2;
        } finally {
            return 3;      // But actually  this block execute successfully
    }
 }

    public static void main(String[] args) {
        System.out.println(function());
    }
}


I have no idea how the JVM implements it, but the simplest way to look at it (at least conceptually) would be:
  1. the return value in the "try" is pushed onto the stack,
  2. then the "finally" block is executed,
  3. the new return value is pushed onto the stack
  4. the function exits, and the return value is popped from the stack, thus ignoring the first one.


What I found in the Java language specification at least defines that your code snippet should return 3. Of course, it does not mention how the JVM should implement this, and what possible optimizations one could do.
Section 14.20.2 defines that
If execution of the try block completes abruptly for any other reason R, then the finally block is executed. Then there is a choice:
  1. If the finally block completes normally, then the try statement completes abruptly for reason R.
  2. If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).
And the start of chapter14 (section 14.1 to be more precise) specifies what a normal and abrupt completion is. For example a return with a given value is an abrupt completion.
Hence in this case, the finally block completes abruptly (reason: return with a given value), so the try will complete abruptly for the same reason (and return 3). This is confirmed in section 14.17 about the return statement as well
If evaluation of the Expression completes normally, producing a value V, then the return statement completes abruptly, the reason being a return with value V.



About finally block ...


Hello friends my Today's question is :

Here is sample code :

        File file = new File("d:/asd.txt"); //Assume this path is not available
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) { // So Exception catch Here
                       e.printStackTrace();
        }
  // So now finally block must execute 
     finally {
            try {
                fileInputStream.close();  // but here again exception comes here
            } catch (IOException e) {
                e.printStackTrace();   // So Exception catch Here
            }finally {
                System.out.println("inner finally");  // This statement executed
            }
            System.out.println("finally"); // Why this statement is not execute .. ?
        }
Provide your Comments and feedback ...Thanks is advance..!!!!