Wednesday, June 22, 2011

Access modifiers in Java

Access modifiers specifies who can access them. There are four access modifiers used in java. They are public, private, protected, no modifer (declaring without an access modifer). Using ‘no modifier’ is also sometimes referred as ‘package-private’ or ‘default’ or ‘friendly’ access. Usage of these access modifiers is restricted to two levels. The two levels are class level access modifiers and member level access modifiers.

 

I) Class level access modifiers (java classes only)


Only two access modifiers is allowed, public and no modifier
  • If a class is ‘public’, then it CAN be accessed from ANYWHERE.
  • If a class has ‘no modifer’, then it CAN ONLY be accessed from ‘same package’.

II) Member level access modifiers (java variables and java methods)

All the four public, private, protected and no modifer is allowed.

  • public and no modifier – the same way as used in class level.
  • private – members CAN ONLY access.
  • protected – CAN be accessed from ‘same package’ and a subclass existing in any package can access.

For better understanding, member level access is formulated as a table:



Access Modifiers

Same Class Same Package Subclass Other packages
public Y Y Y Y
protected Y Y Y N
no access modifier Y Y N N
private Y N N N


First row {public Y Y Y Y} should be interpreted as:

  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same class’.
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘same package’.
  • Y – A member declared with ‘public’ access modifier CAN be accessed by the members of the ‘subclass’.
  • Y – A member declared as ‘public’ CAN be accessed from ‘Other packages’.

Second row {protected Y Y Y N} should be interpreted as:

  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same class’.
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘same package’.
  • Y – A member declared with ‘protected’ access modifier CAN be accessed by the members of the ‘subclass’.
  • N – A member declared with ‘protected’ access modifier CANNOT be accessed by the members of the ‘Other package’.

Similarly interpret the access modifiers table for the third (no access modifier) and fourth (private access modifier) records.

Sunday, June 19, 2011

Overloading vs Overriding

Conceptually overloading and overriding is way different. Only the notion about interface name is same in both cases. Other than that, you cannot find a common thing between them.


Overloading is using the same interface but with different inputs and getting different behaviour as output. Slightly confusing right. I hope by end of this article you may feel better.


Not Overloading
Not Overloading


Overriding is in picture when there is inheritance. When you are inheriting a object there are so many behaviours associated with it. Primarily you are inheriting to use the common behaviour and attributes. But in certain cases, you may not like a particular behaviour. In such cases, you overwrite that behaviour alone in your inherited instance. The interface will be same.

Overloading is not polymorphism. Run time binding is not polymorphism. All these and more are used to exercise the property polymorphism. Polymorphism is a more general property belonging to object-oriented programming parlance and demands a separate article by itself. Let’s discuss that in detail then.

 

Overloading

Now let’s continue to discuss overloading and overriding. I have shown an image of a overloaded truck. I specifically used this image and drawn a wrong mark on it. Because, when I did some research on this topic using internet almost all web pages where ever overloading is discussed this kind of overloaded truck image is used to explain the meaning. Please get it right. Overloading is not adding more and more attributes and interfaces to the object so that it looks bulkier. In fact, when you use overloading for the outsiders view the object will look compact. That is putting more behaviour with same interface. That is your object will look sleek.


Before Overloading
Before Overloading


I have shown two images, one is Harmonium, a classical music instrument from India. Just for understanding it is a very trimmed version of piano. The other is a modern digital keyboard. Harmonium is without overloading and keyboard is after overloading. In a digital keyboard, keys are the interface, in programming method name. Speaker is the output, in programming return type of the method. When the player presses the keys he gives input to the method and gets output as music through the speakers.


After Overloading
After Overloading

Following line is very important to understand the complete correlation. When different input is given you get different out put. Here the interface (method name, keys) is same and output type is same. But the actual input (arguments, key press sequence) and output (returned data, music) is different. This is overloading. Look at the whole object (keyboard), how sleek it is after overloading.

 

Example java source code for overloading:

public class OverloadExample {
  public static void main(String args[]) {
    System.out.println(playMusic("C sharp","D sharp"));
    System.out.println(playMusic("C","D flat","E flat"));
  }
  public static String playMusic(String c, String d) {
    return c+d;
  }
  public static String playMusic(String c, String d, String e){
    return c+d+e;
  }
}

 

Overriding

It is very simple and easy to understand. When you inherit an object, you don’t like certain behaviour and so you replace it with your own. Note the word replace. Because after overriding the old behaviour is completely obsolete. Now look at the image of a monster truck. Here the old small four wheels are replaced with huge wheels to suit the current need. This is overriding.


Overriding


Some specific points about overloading in Java:

A java private method cannot be overridden because in first place it is not accessible to an inheriting object.
Final parameter in the overloaded method, has an interesting behaviour which I leave it for your exercise ;-)

 

An example for overriding from java package:


Implicitly every object in Java is extended from Object class. Object has a method named equals. This implementation compares the passed object with the current object and returns true if the reference are same. In String class you don’t want this behaviour. Therefore, equals method of the Object class is overridden in String class with its own implementation. Here the behaviour is modified to check if the character sequence is same as the compared one and returns true. This is a classic example of overriding.


Difference Between Interface and Abstract Class

  1. Main difference is methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
  2. Variables declared in a Java interface is by default final. An  abstract class may contain non-final variables.
  3. Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
  4. Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
  5. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
  6. A Java class can implement multiple interfaces but it can extend only one abstract class.
  7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
  8. In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.

Java Clone, Shallow Copy and Deep Copy

Clone (κλών) is a Greek word meaning “branch”, referring to the process whereby a new plant can be created from a twig. In biology it is about copying the DNAs. In real world, if you clone Marilyn Monroe, will you get a copy of her with same beauty and characteristics? No, you will not get! This exactly applies to java also. See how java guys are good at naming technologies.

In java, though clone is ‘intended’ to produce a copy of the same object it is not guaranteed. Clone comes with lots of its and buts. So my first advice is to not depend on clones. If you want to provide a handle / method to deliver a copy of the current instance write a kind of factory method and provide it with a good documentation. When you are in a situation to use a third party component and produce copies of it using the clone method, then investigate that implementation carefully and get to know what is underlying. Because when you ask for a rabbit, it may give monkeys!

 

Shallow Copy

 

Generally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. This is nothing but shallow copy. Object class provides a clone method and provides support for the shallow copy. It returns ‘Object’ as type and you need to explicitly cast back to your original object.

Since the Object class has the clone method (protected) you cannot use it in all your classes. The class which you want to be cloned should implement clone method and overwrite it. It should provide its own meaning for copy or to the least it should invoke the super.clone(). Also you have to implement Cloneable marker interface or else you will get CloneNotSupportedException. When you invoke the super.clone() then you are dependent on the Object class’s implementation and what you get is a shallow copy.

 

Deep Copy


When you need a deep copy then you need to implement it yourself. When the copied object contains some other object its references are copied recursively in deep copy. When you implement deep copy be careful as you might fall for cyclic dependencies. If you don’t want to implement deep copy yourselves then you can go for serialization. It does implements deep copy implicitly and gracefully handling cyclic dependencies.

One more disadvantage with this clone system is that, most of the interface / abstract class writers in java forget to put a public clone method. For example you can take List. So when you want to clone their implementations you have to ignore the abstract type and use actual implementations like ArrayList by name. This completely removes the advantage and goodness of abstractness.

When implementing a singleton pattern, if its superclass implements a public clone() method, to prevent your subclass from using this class’s clone() method to obtain a copy overwrite it and throw an exception of type  CloneNotSupportedException.

Note that clone is not for instantiation and initialization. It should not be synonymously used as creating a new object. Because the constructor of the cloned objects may never get invoked in the process. It is about copying the object in discussion and not creating new. It completely depends on the clone implementation. One more disadvantage (what to do there are so many), clone prevents the use of final fields. We have to find roundabout ways to copy the final fields into the copied object.

Clone is an agreement between you, compiler and implementer. If you are confident that you all three have good knowledge of java, then go ahead and use clone. If you have a slightest of doubt better copy the object manually.

Example source code for java clone and shallow copy

class Employee implements Cloneable {
 private String name;
 private String designation;
 public Employee() {
 this.setDesignation("Programmer");
 }
 public String getDesignation() {
 return designation;
 }
 public void setDesignation(String designation) {
 this.designation = designation;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public Object clone() throws CloneNotSupportedException {
 /*
 Employee copyObj = new Employee();
 copyObj.setDesignation(this.designation);
 copyObj.setName(this.name);
 return copyObj;
 */
 return super.clone();
 }
}
public class CloneExample {
 public static void main(String arg[]){
 Employee jwz = new Employee();
 jwz.setName("Jamie Zawinski");
 try {
 Employee joel = (Employee) jwz.clone();
 System.out.println(joel.getName());
 System.out.println(joel.getDesignation());
 } catch (CloneNotSupportedException cnse) {
 System.out.println("Cloneable should be implemented. " + cnse );
 }
 }
}

Output of the above program:

Jamie Zawinski
Programmer

What is a java marker interface?

Java marker interface has no members in it. Marker interface ‘was’ used as a tag to inform a message to the java compiler.

Java Marker Interface Examples:

java.lang.Cloneable
java.io.Serializable
java.util.EventListener

Lets take the java.io.Serializable marker interface. It doesnot has any members defined it it. When a java class is to be serialized, you should intimate the java compiler in some way that there is a possibility of serializing this java class. In this scenario, marker interfaces are used. The java class which may be serialized has to implement the java.io.Serializable marker interface. In such way, we are intimating the java compiler.
From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

Java Serialization

Have you ever seen what is inside a serialized object? I will explain you what is java serialization, then provide you with a sample for serialization. Finally most importantly, lets explore what is inside a serialized object and what it means. That is internals of java serialization and how does it works. If you want to have your own implementation of java serialization, this article will provide you with a good platform to launch.

 

What is Java Serialization?

Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.
Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an object across sessions. This is not the primary purpose of java serialization. Sometimes, when I interview candidates for Java I hear them saying java serialization is used for storing (to preserve the state) an object and retrieving it. They use it synonymously with database. This is a wrong perception for serialization.

 

How do you serialize?


When you want to serialize an object, that respective class should implement the marker interface serializable. It just informs the compiler that this java class can be serialized. You can tag properties that should not be serialized as transient. You open a stream and write the object into it. Java API takes care of the serialization protocol and persists the java object in a file in conformance with the protocol. De-serialization is the process of getting the object back from the file to its original form.

Here protocol means, understanding between serializing person and de-serializing person. What will be the contents of file containing the serialized object? This serves as a guideline to de-serialize. Have a look at the following sample and how its serialized file looks.

 

Sample Source Code for Java Serialization

package com.javapapers.sample;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class SerializationBox implements Serializable {
  private byte serializableProp = 10;
  public byte getSerializableProp() {
    return serializableProp;
  }
}
public class SerializationSample {
  public static void main(String args[]) throws IOException,
      FileNotFoundException, ClassNotFoundException {
    SerializationBox serialB = new SerializationBox();
    serialize("serial.out", serialB);
    SerializationBox sb = (SerializationBox) deSerialize("serial.out");
    System.out.println(sb.getSerializableProp());
  }
  public static void serialize(String outFile, Object serializableObject)
      throws IOException {
    FileOutputStream fos = new FileOutputStream(outFile);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(serializableObject);
  }
  public static Object deSerialize(String serilizedObject)
      throws FileNotFoundException, IOException, ClassNotFoundException {
    FileInputStream fis = new FileInputStream(serilizedObject);
    ObjectInputStream ois = new ObjectInputStream(fis);
    return ois.readObject();
  }
}

 

Exploring Java Serialization


Look at following image. After serializing ‘SerializationBox’ in the above sample code, I opened the output in a hex editor. You can use Notepad++ and hex plugin to open the serialized file.
Let us look at contents byte by byte and find out what they are. It starts with “ac ed”. It is is called STREAM_MAGIC. It is a magic number (java API guys says) that is written to the stream header. It denotes
that is start of serialzed content.


Serialized Output


Similarly every character has a meaning. Actually the serialized file is more bulkier than you would expect, as it has a huge header the meta information of the classes involved and finally the content. Object Serialization Stream Protocol have a look at chapter 6.4.2 Terminal Symbols and Constants. It gives you list of symbols and constants used in serialization.

 

Decrypting Serialized Java Object


In the image, I have underline a unit of information in a separate color for you to easily identify.
ac ed – STREAM_MAGIC – denotes start of serialzed content
00 05 – STREAM_VERSION – serialization version
73 – TC_OBJECT – new Object
72 – TC_CLASSDESC – new Class Descriptor
00 26 – length of the class name
63 6f 6d 2e 6a 61 76 61 70 61 70 65 72 73 2e 73 61 6d 70 6c 65 2e 53 65 72 69 61 6c 69 7a 61 74 69 6f 6e 42 6f 78 – class name
57 fc 83 ca 02 85 f0 18 – SerialVersionUID
02 – this object is serializable
00 01 – count of properties in the serialzed class – one property in our example
42 00 10 – private byte
73 65 72 69 61 6c 69 7a 61 62 6c 65 50 72 6f 70 78 70 – property name – serializableProp in our example
0a – 10 the value – This is the persisted value of the property in our sample.

Java variables can be categorized into the following seven types:

  1. Class Variable
  2. Instance Variable
  3. Array Component Variable
  4. Method Parameter Variable
  5. Constructor Parameter Variable
  6. Exception Handler Parameter Variable
  7. Local Variable

1) Class Variable

A java class variable is a field declared using the keyword static within a java class, or with or without the keyword static within a java interface declaration.

2) Instance Variable


Java variables that are declared without static keyword are instance variables.

3) Array Component

Array components are unnamed java variables that are created and initialized to default values whenever a new java array object is created.

4) Method Parameter

Java variables declared in the method declaration signature are method parameter variables. Whenever a java method is invoked a variable is created in the same name as it is declared.

5) Constructor Parameter

This is similar to the java method parameter variable. The same way, for all the java variables declared in the constructor a variable is created whenever it is invoked.

6) Exception Handler Parameter

Java variables that are declared in the catch clause of a java exception handling mechanism. Whenever a java exception is caught, exception handler parameter variable is created.

7) Local Variable

Java variables that are declared in a block inside a java method or for loop is called a java local variable.
Reference: Java Language Specification 4.12.3


Java this Keyword

This definition:

Java’s ‘this’ keyword is used to refer the current instance of the method on which it is used.

 

Following are the ways to use this


1) To specifically denote that the instance variable is used instead of static or local variable.That is,
private String javaFAQ;
void methodName(String javaFAQ) {
this.javaFAQ = javaFAQ;
}
Here this refers to the instance variable. Here the precedence is high for the local variable. Therefore the absence of the “this” denotes the local variable. If the local variable that is parameter’s name is not same as instance variable then irrespective of this is used or not it denotes the instance variable.
2) This is used to refer the constructors

public JavaQuestions(String javapapers) {
this(javapapers, true);
}
This invokes the constructor of the same java class which has two parameters.

3) This is used to pass the current java instance as parameter
obj.itIsMe(this);
4) Similar to the above this can also be used to return the current instance
CurrentClassName startMethod() {
return this;
}
Note: This may lead to undesired results while used in inner classes in the above two points. Since this will refer to the inner class and not the outer instance.

5) This can be used to get the handle of the current class
Class className = this.getClass(); // this methodology is preferable in java
Though this can be done by, Class className = ABC.class; // here ABC refers to the class name and you need to know that!

As always, this is associated with its instance and this will not work in static methods.



Java Static

Java Static Variables

 

  • Java instance variables are given separate memory for storage. If there is a need for a variable to be common to all the objects of a single java class, then the static modifier should be used in the variable declaration.
  • Any java object that belongs to that class can modify its static variables.
  • Also, an instance is not a must to modify the static variable and it can be accessed using the java class directly.
  • Static variables can be accessed by java instance methods also.
  • When the value of a constant is known at compile time it is declared ‘final’ using the ‘static’ keyword.

 

Java Static Methods

 

  • Similar to static variables, java static methods are also common to classes and not tied to a java instance.
  • Good practice in java is that, static methods should be invoked with using the class name though it can be invoked using an object. ClassName.methodName(arguments) or objectName.methodName(arguments)
  • General use for java static methods is to access static fields.
  • Static methods can be accessed by java instance methods.
  • Java static methods cannot access instance variables or instance methods directly.
  • Java static methods cannot use the ‘this’ keyword.

 

Java Static Classes

 

  • For java classes, only an inner class can be declared using the static modifier.
  • For java a static inner class it does not mean that, all their members are static. These are called nested static classes in java.

    Java (JVM) Memory Types

    Java has only two types of memory when it comes to JVM. Heap memory and Non-heap memory. All the other memory jargon's you hear are logical part of either of these two.

     

    Heap Memory

    Class instances and arrays are stored in heap memory. Heap memory is also called as shared memory. As this is the place where multiple threads will share the same data.


                                 

     

     

    Non-heap Memory

    It comprises of ‘Method Area’ and other memory required for internal processing. So here the major player is ‘Method Area’.

     

    Method Area


    As given in the last line, method area is part of non-heap memory. It stores per-class structures, code for methods and constructors. Per-class structure means runtime constants and static fields.
    The above three (heap memory, non-heap memory and method area) are the main jargon when it comes to memory and JVM. There are some other technical jargon you might have heard and I will summarize them below.

     

    Memory Pool

    Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory.

     

    Runtime Constant Pool

    A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method area.


                            jvm memory

     

    Java Stacks or Frames

    Java stacks are created private to a thread. Every thread will have a program counter (PC) and a java stack. PC will use the java stack to store the intermediate values, dynamic linking, return values for methods and dispatch exceptions. This is used in the place of registers.

     

    Memory Generations

    HotSpot VM’s garbage collector uses generational garbage collection. It separates the JVM’s memory into and they are called young generation and old generation.

     

    Young Generation


    Young generation memory consists of two parts, Eden space and survivor space. Shortlived objects will be available in Eden space. Every object starts its life from Eden space. When GC happens, if an object is still alive and it will be moved to survivor space and other dereferenced objects will be removed.

     

    Old Generation – Tenured and PermGen


    Old generation memory has two parts, tenured generation and permanent generation (PermGen). PermGen is a popular term. We used to error like PermGen space not sufficient.
    GC moves live objects from survivor space to tenured generation. The permanent generation contains meta data of the virtual machine, class and method objects.

     

    Discussion:

    Java specification doesn’t give hard and fast rules about the design of JVM with respect to memory. So it is completely left to the JVM implementers. The types of memory and which kind of variable / objects and where they will be stored is specific to the JVM implementation.

     

    Key Takeaways

    • Local Variables are stored in Frames during runtime.
    • Static Variables are stored in Method Area.
    • Arrays are stored in heap memory.

     

    References:

    Java Final Keyword

    • A java variable can be declared using the keyword final. Then the final variable can be assigned only once.
    • A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces the constructors to initialise it.
    • Java classes declared as final cannot be extended. Restricting inheritance!
    • Methods declared as final cannot be overridden. In methods private is equal to final, but in variables it is not.
    • final parameters – values of the parameters cannot be changed after initialization. Do a small java exercise to find out the implications of final parameters in method overriding.
    • Java local classes can only reference local variables and parameters that are declared as final.
    • A visible advantage of declaring a java variable as static final is, the compiled java class results in faster performance.

     

    A discussion inviting controversy on java final keyword:

    ‘final’ should not be called as constants. Because when an array is declared as final, the state of the object stored in the array can be modified. You need to make it immutable in order not to allow modifcations. In general context constants will not allow to modify. In C++, an array declared as const will not allow the above scenario but java allows. So java’s final is not the general constant used across in computer languages.
    A variable that is declared static final is closer to constants in general software terminology. You must instantiate the variable when you declare it static final.
    Definition as per java language specification (third edition) – 4.12.4 is “A final variable may only be assigned to once.”(§4.1.2)

    Java language specification tries to redefine the meaning of constant in the following way!
    We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).

    Java Pass By Value and Pass By Reference.

    Pass by value in java means passing a copy of the value to be passed. Pass by reference in java means the passing the address itself. In Java the arguments are always passed by value. Java only supports pass by value.


    With Java objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same Java object. Java primitives too are passed by value.

    Check list for Internationalization (I18n)

    This check list for Internationalization (I18n) will cater to the need of programmers irrespective of the language java /dot net/ j2ee / any other.

    Translatable items

    • GUI – Labels and Menu items
    • User messages including third party component generated
    • Log / system generated messages
    • Help – Online help / manual and other deliverable documentation
    • Installation notes / guide / setup information
    • Symbols (Rs., $, …)
    • Icons, Images and Colors
    • Sound
    • Animation

     

    Formatting and Processing items

    • Time, Date, and Calendar
    • Numeric, Monetary, and Metric
    • Personal Names, Honorifics, and Titles
    • Maps / Addresses
    • Layout (Like narrow / broad)
    • Sound-to-Text / speech recognition

     

    Technical

    • Equality checking (String / Character matching)
    • Sorting
    • Text length / wrapping
    • Position / direction of text / objects
    • Encoding Methods
    • Device Input (Keyboard and Input Methods)
    • Device Output (Font Management, Rendering, and Output Methods)

    Java’s toLowerCase() has got a surprise for you!

    Have you ever encountered a surprise while using toLowerCase()? This is a widely used method when it comes to strings and case conversion. There is a nice little thing you should be aware of.





    toLowerCase() respects internationalization (i18n). It performs the case conversion with respect to your Locale. When you call toLowerCase(), internally toLowerCase(Locale.getDefault()) is getting called. It is locale sensitive and you should not write a logic around it interpreting locale independently.


    import java.util.Locale;
     
    public class ToLocaleTest {
        public static void main(String[] args) throws Exception {
            Locale.setDefault(new Locale("lt")); //setting Lithuanian as locale
            String str = "\u00cc";
      System.out.println("Before case conversion is "+str+" and length is "+str.length());// Ì
            String lowerCaseStr = str.toLowerCase();
      System.out.println("Lower case is "+lowerCaseStr+" and length is "+lowerCaseStr.length());// i?`
        }
    } 
     
    In the above program, look at the string length before and after conversion. It will be 1 and 3. Yes the length of the string before and after case conversion is different. Your logic will go for a toss when you depend on string length on this scenario. When your program gets executed in a different environment, it may fail. This will be a nice catch in code review.

    To make it safer, you may use another method toLowerCase(Locale.English) and override the locale to English always. But then you are not internationalized.
    So the crux is, toLowerCase() is locale specific.

    Java Double Brace Initialization

    Double brace initialization is a combination of two separate process in java. There are two { braces involved in it. If you see two consecutive curly braces { in java code, it is an usage of double brace initialization.

     

    Java Double Brace Initialization

    First brace is creation of an anonymous inner class. Without considering the second brace if you see the first brace alone then its nothing new for us. We have created many anonymous inner classes in such a way.
    Second brace is an initialization block. That too you have seen in it a class for initialization. You may have used a static initialization block. When you use the initialization block for an anonymous inner class it becomes java double brace initialization. The inner class created will have a reference to the enclosing outer class. That reference can be used using the ‘this’ pointer.

     

    Example for double brace initialization

    class JavaPapers {
    ....
    ....
    add(new JPanel() {{
    setLayout(...);
    setBorder(...);
    ...
    }}
    );
    
    }

    Uses of double brace initialization

    Using double brace initialization, we can initialize collections. Though people say, it is easier to initialize a constant collection using double brace initialization. I don’t see any advantage in using double brace initialization to initialize collections. In jdk 1.7 there is going to be an exclusive construct for that. Then java double brace initialization will become completely obsolete.
    ...
    myMethod(
      new ArrayList<String>() {{
         add("java");
         add("jsp");
         add("servlets");
      }}
    );
    ...
    

    Note on double brace initialization

     

    Serialization of non-static inner class has an issue. The outer class will also get serialized. Because the inner class has got a reference to the outer class and it is implicit. Since it is implicit, it cannot be marked as transient. This issue is also applicable for double brace initialization.

    Java Closures

    In this article, I will explain what a closure is and clear the confusion surrounding anonymous inner classes and closures, then java’s current situation with respect to closures.

    First I want to emphasize the below two points:
    1. As of JDK 1.6 we don’t have closures in java.
    2. Annonymous inner classes in java are not closures.

    Definition of closure

    Function types and inline function-valued expression are called closures. Let me decrypt this definition for you. An anonymous function that contains some context surrounding it as a snapshot and can be passed as a parameter. This closure defintion has two parts. First one is about callback. That is, a pointer to a function that can be passed as a parameter. Second part of the definition is, this callback function will enclose some contextual information surrounding it as a snapshot and passed along with the function.
    A closure is also referred to as a ‘first class object’ which can refer to attributes from its enclosing scope. As defined by Christopher Strachey in ‘Understanding Programming Languages’, a first class object can be stored in a data structure, passed as a parameter, can be returned from a function, can be constructed at runtime and independent of any identity.

                                                    

    In case if you are curious in Mathematics a closure is, when you operate on a members fo a set and if the resultant is always a member of that set then its called a closure.

    Anonymous inner class is not closure

    Anonymous classes in java are close to being called as a closure. They don’t 100% support the definition but come close to it and thats why we see lot of literature calling anonymous inner classes as closure. Why do I say its not 100%? An anonymous inner class can access “only” the final local variable of the enclosing method. It is because of this restriction, anonymous inner class in java is not a closure.
    If you remember the memory management in java, you can recall that the local variables are stored in a stack. These java stacks are created when the method starts and destroyed when it returns. Unlike local variables, final fields are stored in method area which lives longer even after the return of the method. If we want to make anonymous inner class as a closure, then we should allow it to access all the fields surrounding it. But, as per the current memory management, they will be destroyed and will not be accessible after the method has returned.

     

    Closure in Java

    In that case will we get closure in java in future? We have a specification written by Peter Ahe, James Gosling, Neal Gafter and Gilad Bracha on closures for java. It gives detailed description of how a closure can be implemented in java and example code on how to use them. We have JSR 335 for closures in java named as Lambda Expressions for the Java Programming Language.

    Tuesday, June 14, 2011

    My first date with Java


    Who says love at first site is not possible, well my love on Java was of course love at first sight. And I still feel that same magic on me by Him.

    Life is beautiful from here on . . .

    In order to tell you the story, we have to travel back in time. Those were my collage days . . . I met him for the first time in a boring, typical class. I was seldom attentive in classes, the intro sucked. Well, as usually I was disappointed that this class is as lackluster as others. I was looking outside from the window. It is clear, sunny day. It was almost 3 o clock in the evening, probably everyone are napping. Me stuck in a deadly numb class. As usual I was trying to act as if I am listening, as much disappointed I was that much attentive I became when I heard a sweet voice, a sweet song of Java flowing through my ears. Startling it was! It was for the first time I ever concentrated in computers class. I was listening and listening, and nothing is making me mad, on contrary it’s so soothing to my heart. Ever in my life that any class gave me such a relief. All it said was, “Hello world”.  That’s it, all it did was Hello, and I was totally flat at him, nothing he did ever changed my mind on him, fallen deeply into abyss of his concepts. Tangled in the web Object oriented programming. Well, until now there was no turning back.

    Well, it is not the first time that I was so fed up with my classes, the worst part is the practices, nonetheless in the starting year of my college I was a first bencher. Used to sit in the first place and first bench, latter upon making few friends, I shifted to last. My friends are such a fun and so cool; they gave me the best part of my life. Specially my gang, gang that identifies itself for its menace. We are so tough in the whole college, never used to read, never used to write exams, never even used to pass the exams, of course the internal exams. Everyone were so good at one day batsmen-ship, that they used to play it with such a violence, and aggression, that they used to always pass, exception with me is that my passion on studies always fetched me a topper in my finals with just a single day championship.  Always, we are very jolly. They are so hostile to reading. Any studious girl / boy used to antagonize them. We used to compete on who gets the less marks. The one who gets the one digit mark is the idol, hero for the gang. And how we make boring class into our playground is total awesome. Our lecturers and professors are so fed up with us. We were the most fun, and naughtiest gang in the whole college. There are no embellishments to my college days, they are exactly what I say here.  lovable, I am not exaggerating on any.  They are that good, utterly standalones. Our professors used to hold grudges on us. Well during these days, when I was totally free bird with no kind of disciple and no aim in my life other than having fun . .  . inexplicable reckless days, with none to worry of, none to take care of, totally a free bird in a flock of other birds,  in my final year, I met him.

    My friends left me, leaving me alone with Java, They gave up on me, they thought no one can ever bring me back to their world. I used to see nothing but Java. I was so happy that it was in my curriculum, the sweetness of the first programs . . . it is so perspicuous that I was in love with him, totally drenched in its lines of codes. It’s a absurd, and abstruse relation. He did had a strong poise of spell on me, with his charms and his implicit constructors, that are encapsulated in a class. His inheritance was mesmerizing, I am like totally blended into him for his polymorphic nature. His masculine  implicit constructors and parameterized constructors is all I used to see and here. His new instances, cool. I was in total trance. I was deeply in love with him. Oh! My dream Language.


    I used to wake up from my nightmares saying implement this method of the interface in the class to achieve that functionality. Make him full, fill him in with ever functionality to make him powerful. This is all I used to dream. Well, in my lab, it was for first time I had a date with him. Finally, 2 hours of lab and guess what I get splendid time I ever had with him. Implemented all his concepts, so he could be happy. Javac / .java / Java are three dialogues that were keep coming out of my mouth. We in deed had a very good time that very first day in my lab. He always used to ask what he wanted without shouting at me. He used print it on the console just for me. Indeed it was so outstanding date that we choose to stay together all our life, he promised not to leave me and I promised not to leave him.

    Well, in the end we both are happy in each other solace. The story ends and we go back to our homes.  Happily ever after . . .




    So, here starts my love on Java; he never left, even now he is still with me, holding my hand . . . He never lets me go no matter how hard I try. After all a girl needs: someone who won't give up on her no matter how hard she tries to push them away . . . I am lucky. Thus a new journey begun . . .