Sunday, 5 April 2015

Java Keywords

Java Language Keywords

Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.




abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
* not used
** added in 1.2
*** added in 1.4































































































Sunday, 29 March 2015

How to make a java class immutable

 

How to make a java class immutable

Benefits of making a class immutable

Lets first identify benefits of making a class immutable. Immutable classes are
  1. are simple to construct, test, and use
  2. are automatically thread-safe and have no synchronization issues
  3. do not need a copy constructor
  4. do not need an implementation of clone
  5. allow hashCode to use lazy initialization, and to cache its return value
  6. do not need to be copied defensively when used as a field
  7. make good Map keys and Set elements (these objects must not change state while in the collection)
  8. have their class invariant established once upon construction, and it never needs to be checked again
  9. always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state

Guidelines to make a class immutable

1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
This principle says that for all mutable properties in your class, do not provide setter methods. Setter methods are meant to change the state of object and this is what we want to prevent here.

2) Make all fields final and private
This is another way to increase immutability. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.

3) Don’t allow subclasses to override methods
The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.

4) Special attention when having mutable instance variables
Always remember that your instance variables will be either mutable or immutable. Identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.

A more sophisticated approach is to make the constructor private and construct instances in factory 
methods.

Lets add all above rules and make something concrete class implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.Date;
/**
* Always remember that your instance variables will be either mutable or immutable.
* Identify them and return new objects with copied content for all mutable objects.
* Immutable variables can be returned safely without extra effort.
* */
public final class ImmutableClass
{
    /**
    * Integer class is immutable as it does not provide any setter to change its content
    * */
    private final Integer immutableField1;
    /**
    * String class is immutable as it also does not provide setter to change its content
    * */
    private final String immutableField2;
    /**
    * Date class is mutable as it provide setters to change various date/time parts
    * */
    private final Date mutableField;
    //Default private constructor will ensure no unplanned construction of class
    private ImmutableClass(Integer fld1, String fld2, Date date)
    {
        this.immutableField1 = fld1;
        this.immutableField2 = fld2;
        this.mutableField = new Date(date.getTime());
    }
    //Factory method to store object creation logic in single place
    public static ImmutableClass createNewInstance(Integer fld1, String fld2, Date date)
    {
        return new ImmutableClass(fld1, fld2, date);
    }
    //Provide no setter methods
    /**
    * Integer class is immutable so we can return the instance variable as it is
    * */
    public Integer getImmutableField1() {
        return immutableField1;
    }
    /**
    * String class is also immutable so we can return the instance variable as it is
    * */
    public String getImmutableField2() {
        return immutableField2;
    }
    /**
    * Date class is mutable so we need a little care here.
    * We should not return the reference of original instance variable.
    * Instead a new Date object, with content copied to it, should be returned.
    * */
    public Date getMutableField() {
        return new Date(mutableField.getTime());
    }
    @Override
    public String toString() {
        return immutableField1 +" - "+ immutableField2 +" - "+ mutableField;
    }
}
Now its time to test our class:

badge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class TestMain
{
    public static void main(String[] args)
    {
        ImmutableClass im = ImmutableClass.createNewInstance(100,"test", new Date());
        System.out.println(im);
        tryModification(im.getImmutableField1(),im.getImmutableField2(),im.getMutableField());
        System.out.println(im);
    }
    private static void tryModification(Integer immutableField1, String immutableField2, Date mutableField)
    {
        immutableField1 = 10000;
        immutableField2 = "test changed";
        mutableField.setDate(10);
    }
}
Output: (content is unchanged)
100 - test - Tue Oct 30 21:34:08 IST 2012
100 - test - Tue Oct 30 21:34:08 IST 2012
As it can be seen that even changing the instance variables using their references does not change their value, so the class is immutable.

How prepared statement works

How prepared statement works?

Most relational databases handles a JDBC / SQL query in four steps:
  1. Parse the incoming SQL query
  2. Compile the SQL query
  3. Plan/optimize the data acquisition path
  4. Execute the optimized query / acquire and return data
A Statement will always proceed through the four steps above for each SQL query sent to the database. A Prepared Statement pre-executes steps (1) -- (3) in the execution process above. Thus, when creating a Prepared Statement some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.

Advantages of using prepared statement over simple statement

  • Pre-compilation and DB-side caching of the SQL statement leads to overall faster execution and the ability to reuse the same SQL statement in batches.
  • Automatic prevention of SQL injection attacks by builtin escaping of quotes and other special characters. Note that this requires that you use any of the PreparedStatement setXxx() methods to set the values and not use inline the values in the SQL string by string-concatenating.
  • Apart from above two main usage, prepared statements makes it easy to work with complex objects like BLOBs and CLOBs.


Execution of prepared statements requires following steps:
1) Make a database connection
2) Set values and execute prepared statement
Pre-requisites include setting up a database schema and creating a table at least.

CREATE SCHEMA 'JDBCDemo' ;
CREATE TABLE 'JDBCDemo'.'EMPLOYEE'
(
   'ID' INT NOT NULL DEFAULT 0 ,
    'FIRST_NAME' VARCHAR(100) NOT NULL ,
    'LAST_NAME' VARCHAR(100) NULL ,
    'STAT_CD' TINYINT NOT NULL DEFAULT 0
);
Let’s write above steps in code:

1) Make a database connection

Though we have already learned about it in making JDBC connection, lets recap with this simple code snippet.




Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
    .getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");

2) Set values and execute prepared statement

This is the main step and core part in the post. It requires creating a Statement object and then using it’s executeQuery() method.

PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setInt(1, 87);
pstmt.setString(2, "Ganesh");
pstmt.setString(3, "More");
pstmt.setInt(4, 5);
int affectedRows = pstmt.executeUpdate();
Let’s see the whole code in working.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class PreparedStatementDemo
{
    public static void main(String[] args)
    {
        Connection connection = null;
        PreparedStatement pstmt = null;
        String sql = "INSERT INTO EMPLOYEE (ID,FIRST_NAME,LAST_NAME,STAT_CD) VALUES (?,?,?,?)";
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBCDemo", "root", "password");
             
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, 87);
            pstmt.setString(2, "Ganesh");
            pstmt.setString(3, "More");
            pstmt.setInt(4, 5);
            int affectedRows = pstmt.executeUpdate();
            System.out.println(affectedRows + " row(s) affected !!");
        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                pstmt.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
Output:
1 row(s) affected !!

Monday, 9 February 2015

How hash map works in java

Hashing :How hash map works in java or How get() method works internally

One of the most darling question of the core java interviewers is How hash map works in java or internal.implementation of hashmap. Most of the candidates rejection chances increases if the candidate do not give the satisfactory explanation . This question shows that candidate has good knowledge of Collection . So this question should be in your to do list before appearing for the interview.

How Hashmap works in Java

HashMap works on the principle of Hashing .  To understand Hashing , we should understand the three terms first   i.e  Hash Function , Hash Value and Bucket .

What is Hash Function , Hash Value  and Bucket ?

hashCode() function  which returns an integer value is the Hash function. The important point to note that ,  this method is present in.

This is the code for the hash function(also known as hashCode method) in Object Class :

    public native int hashCode();

The most important point to note from the above line :  hashCode method return  int value .
So the Hash value is the int value returned by the hash function .


    So summarize the terms in the diagram below :
                   


how hash  map works in java










What is bucket ?
A bucket is used to store key value pairs . A bucket can have multiple key-value pairs . In hash map, bucket used simple linked list to store objects .



After understanding the terms we are ready to move next step , How hash map works in java or How get() works internally in java .


Code inside Java Api (HashMap class internal implementation) for HashMap get(Obejct key) method 

1.  Public  V get(Object key)
   {
2.     if (key ==null)
3.     //Some code
    
4.     int hash = hash(key.hashCode());
    
5.     // if key found in hash table then  return value
6.     //    else return null
   }

Hash map works on the principle of hashing 

HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of  Entry object . So thinking that Only value is stored  in the bucket is not correct and will not give a good impression on the interviewer .

* Whenever we call get( Key k )  method on the HashMap object . First it checks that whether key is null or not .  Note thatthere can only be one null key in HashMap .  


If key is null , then Null keys always map to hash 0, thus index 0.

If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode()  ,so after key.hashCode() returns hashValue , line 4 looks like

4.                int hash = hash(hashValue)

 , and now ,it applies returned hashValue into its own hashing function .


We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is ,It defends against poor quality hash functions.

Now step 4 final  hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex) .  

Interviewer:    What if  when two different keys have the same hashcode ?

Solution, equals() method comes to rescue.Here candidate gets puzzled. Since bucket is one and we have two objects with the same hashcode .Candidate usually forgets that bucket is a simple linked list.

The bucket is the linked list effectively . Its not a LinkedList as in a java.util.LinkedList - It's a separate (simpler) implementation just for the map .

So we traverse through linked list , comparing keys in each entries using keys.equals() until it return true.  Then the corresponding entry object Value is returned .


how hashmap works internally in java







One of  our readers Jammy  asked a very good  question 

When the functions 'equals' traverses through the linked list does it traverses from start to end one by one...in other words brute method. Or the linked list is sorted based on key and then it traverses? 

Answer is when an element is added/retrieved, same procedure follows:

 
a. Using key.hashCode() [ see above step 4],determine initial hashvalue for the key

b. Pass intial hashvalue as hashValue  in    hash(hashValue) function, to calculate the final hashvalue.

c. Final hash value is then passed as a first parameter in the indexFor(int ,int )method .
    The second parameter is length which is a constant in HashMap Java Api , represented by                             DEFAULT_INITIAL_CAPACITY

    The default  value of DEFAULT_INITIAL_CAPACITY is 16 in HashMap Java Api .

 indexFor(int,int) method  returns the first entry in the appropriate bucket. The linked list in the bucket is then iterated over - (the end is found and the element is added or the key is matched and the value is returned )


Explanation about indexFor(int,int) is below :

/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
    return h & (length-1);
}


The above function indexFor() works because Java HashMaps always have a capacity, i.e. number of buckets, as a power of 2.
 Let's work with a capacity of 256,which is 0x100, but it could work with any power of 2. Subtracting 1
from a power of 2 yields the exact bit mask needed to bitwise-and with the hash to get the proper bucket index, of range 0 to length - 1.
256 - 1 = 255
0x100 - 0x1 = 0xFF
E.g. a hash of 257 (0x101) gets bitwise-anded with 0xFF to yield a bucket number of 1.



Interviewer:    What if  when two  keys are same and have the same hashcode ?
If key needs to be inserted and already inserted hashkey's hashcodes are same, and keys are also same(via reference or using equals() method)  then override the previous key value pair with the current key value pair.

The other important point to note is that in Map ,Any class(String etc.) can serve as a key if and only if it overrides the equals() and hashCode() method .


Interviewer:  How will you measure the performance of HashMap?

According to Oracle Java docs,  

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. 

The capacity is the number of buckets in the hash table( HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.), and the initial capacity is simply the capacity at the time the hash table is created. 


The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

In HashMap class, the default value of load factor is (.75) .

Interviewer : What is the time complexity of Hashmap get() and put() method ?

The hashmap implementation provides constant time performance for (get and put) basic operations
i.e the complexity of get() and put() is O(1) , assuming the hash function disperses the elements properly among the buckets. 

Interviewer : What is the difference between HashMap and ConcurrentHashMap ?

It is also one of the popular interview question on HashMap , you can find the answer here 
HashMap vs ConcurrentHashMap 


If you still have any doubts then please write in comments .
Source of image : http://ru.wikipedia.org

Thursday, 29 January 2015

Java Version Changes history

Java Version Changes history 


The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community Process (JCP), which uses Java Specification Requests (JSRs) to propose and specify additions and changes to the Java platform. The language is specified by the Java Language Specification (JLS); changes to the JLS are managed under JSR 901



In addition to the language changes, much more dramatic changes have been made to the Java Class Library over the years, which has grown from a few hundred classes in JDK 1.0 to over three thousand in J2SE 5. Entire new APIs, such as Swing and Java2D, have been introduced, and many of the original JDK 1.0 classes and methods have been deprecated. Some programs allow conversion of Java programs from one version of the Java platform to an older one (for example Java 5.0 backported to 1.4) (see Java backporting tools).


1  JDK Alpha and Beta (1995)
2  JDK 1.0 (January 23, 1996)
3  JDK 1.1 (February 19, 1997)
4  J2SE 1.2 (December 8, 1998)
5  J2SE 1.3 (May 8, 2000)
6  J2SE 1.4 (February 6, 2002)
7  J2SE 5.0 (September 30, 2004)
8  Java SE 6 (December 11, 2006)
8. 1 Java 6 updates
9  Java SE 7 (July 28, 2011)
9. 1 Java 7 updates
10  Java SE 8 (March 18, 2014)
10. 1 Java 8 updates
11  Java SE 9

12  Java SE 10



JDK 1.0 (January 23, 1996)

Originally called Oak. Initial release The first stable version, JDK 1.0.2, is called Java 1.

Note : In versions of Java and the JDK up to 1.0.1, private and protected keywords could be used together to create yet another form of protection that would restrict access to methods or variables solely to subclasses of a given class. As of 1.0.2, this capability has been removed from the language.


JDK 1.1 (February 19, 1997)

Major additions included:

an extensive retooling of the AWT event model
inner classes added to the language
JavaBeans
JDBC
RMI
reflection which supported Introspection only, no modification at runtime was possible.
JIT(Just In Time) compiler on Microsoft Windows platforms, produced for JavaSoft by Symantec

J2SE 1.2 (December 8, 1998)

Codename Playground. This and subsequent releases through J2SE 5.0 were rebranded retrospectively Java 2 and the version name "J2SE" (Java 2 Platform, Standard Edition) replaced JDK to distinguish the base platform from J2EE (Java 2 Platform, Enterprise Edition) and J2ME (Java 2 Platform, Micro Edition). This was a very significant release of Java as it tripled the size of the Java platform to 1520 classes in 59 packages. Major additions included:

strictfp keyword
the Swing graphical API was integrated into the core classes
Sun's JVM was equipped with a JIT compiler for the first time
Java plug-in
Java IDL, an IDL implementation for CORBA interoperability
Collections framework

J2SE 1.3 (May 8, 2000)

Codename Kestrel. The most notable changes were:

HotSpot JVM included (the HotSpot JVM was first released in April 1999 for the J2SE 1.2 JVM)
RMI was modified to support optional compatibility with CORBA
Java Naming and Directory Interface (JNDI) included in core libraries (previously available as an extension)
Java Platform Debugger Architecture (JPDA)
JavaSound
Synthetic proxy classes

J2SE 1.4 (February 6, 2002)
Codename Merlin. This was the first release of the Java platform developed under the Java Community Process as JSR 59. Major changes included:

Language changes

assert keyword (Specified in JSR 41.)
Library improvements
regular expressions modeled after Perl regular expressions
exception chaining allows an exception to encapsulate original lower-level exception
Internet Protocol version 6 (IPv6) support
non-blocking IO (named New Input/Output, NIO) (Specified in JSR 51.)
logging API (Specified in JSR 47.)
image I/O API for reading and writing images in formats like JPEG and PNG
integrated XML parser and XSLT processor (JAXP) (Specified in JSR 5 and JSR 63.)
integrated security and cryptography extensions (JCE, JSSE, JAAS)
Java Web Start included (Java Web Start was first released in March 2001 for J2SE 1.3) (Specified in JSR 56.)
Preferences API (java.util.prefs)
Support and security updates for Java 1.4 ended in October 2008.

J2SE 5.0 (September 30, 2004)

Codename Tiger. Originally numbered 1.5, which is still used as the internal version number. The number was changed to "better reflect the level of maturity, stability, scalability and security of the J2SE. This version was developed under JSR 176.

J2SE 5.0 entered its end-of-public-updates period on April 8, 2008; updates are no longer available to the public as of November 3, 2009. Updates were available to Oracle Customers until May 2014.

Tiger added a number of significant new language features:

Generics: Provides compile-time (static) type safety for collections and eliminates the need for most typecasts (type conversion). (Specified by JSR 14.)

Metadata: Also called annotations; allows language constructs such as classes and methods to be tagged with additional data, which can then be processed by metadata-aware utilities. (Specified by JSR 175.)

Autoboxing/unboxing: Automatic conversions between primitive types (such as int) and primitive wrapper classes (such as Integer). (Specified by JSR 201.)

Enumerations: The enum keyword creates a typesafe, ordered list of values (such as Day.MONDAY, Day.TUESDAY, etc.). Previously this could only be achieved by non-typesafe constant integers or manually constructed classes (typesafe enum pattern). (Specified by JSR 201.)

Varargs: The last parameter of a method can now be declared using a type name followed by three dots (e.g. void drawtext(String... lines)). In the calling code any number of parameters of that type can be used and they are then placed in an array to be passed to the method, or alternatively the calling code can pass an array of that type.

Enhanced for each loop: The for loop syntax is extended with special syntax for iterating over each member of either an array or any Iterable, such as the standard Collection classes. (Specified by JSR 201.)

Fix the previously broken semantics of the Java Memory Model, which defines how threads interact through memory.

Static imports

There were also the following improvements to the standard libraries:

Automatic stub generation for RMI objects.

Swing: New skinnable look and feel, called synth.

The concurrency utilities in package java.util.concurrent.

Scanner class for parsing data from various input streams and buffers.

Java 5 is the last release of Java to officially support the Microsoft Windows 9x line (Windows 95, Windows 98, Windows ME), while Windows Vista is the newest version of Windows that J2SE 5 was supported on prior to Java 5 going end of life in October 2009.

Java 5 Update 5 (1.5.0_05) is the last release of Java to work without any problems on Windows NT 4.0.

Java 5 is the default version of Java installed on Apple Mac OS X 10.5 (Leopard). Java 6 can be installed and set as the default to be used on 64-bit (Core 2 Duo and higher) processor machines. Java 6 is also supported by 32-bit machines running Mac OS X 10.6 (Snow Leopard).

Java SE 6 (December 11, 2006)

Codename Mustang. As of this version, Sun replaced the name "J2SE" with Java SE and dropped the ".0" from the version number. Internal numbering for developers remains 1.6.0. This version was developed under JSR 270.

During the development phase, new builds including enhancements and bug fixes were released approximately weekly. Beta versions were released in February and June 2006, leading up to a final release that occurred on December 11, 2006.

Major changes included in this version:

Support for older Win9x versions dropped; unofficially, Java 6 Update 7 was the last release of Java shown to work on these versions of Windows.[citation needed] This is believed[by whom?] to be due to the major changes in Update 10.

Scripting Language Support (JSR 223): Generic API for tight integration with scripting languages, and built-in Mozilla JavaScript Rhino integration

Dramatic performance improvements for the core platform, and Swing.

Improved Web Service support through JAX-WS (JSR 224)

JDBC 4.0 support (JSR 221).

Java Compiler API (JSR 199): an API allowing a Java program to select and invoke a Java Compiler programmatically.

Upgrade of JAXB to version 2.0: Including integration of a StAX parser.

Support for pluggable annotations (JSR 269)

Many GUI improvements, such as integration of SwingWorker in the API, table sorting and filtering, and true Swing double-buffering (eliminating the gray-area effect).

JVM improvements include: synchronization and compiler performance optimizations, new algorithms and upgrades to existing garbage collection algorithms, and application start-up performance.


Java 6 reached the end of its supported life in February 2013, at which time all public updates, including security updates, were scheduled to be stopped.Oracle released one more update to Java 6 in March 2013, which patched some security vulnerabilities.


Java SE 7 (July 28, 2011)

Java 7 (codename Dolphin) is a major update that was launched on July 7, 2011 and was made available for developers on July 28, 2011.[96] The development period was organized into thirteen milestones; on June 6, 2011, the last of the thirteen milestones was finished. On average, 8 builds (which generally included enhancements and bug fixes) were released per milestone. The feature list at the OpenJDK 7 project lists many of the changes.

Additions in Java 7 include:

JVM support for dynamic languages, with the new invokedynamic bytecode under JSR-292,
following the prototyping work currently done on the Multi Language Virtual Machine

Compressed 64-bit pointers (available in Java 6 with -XX:+UseCompressedOops)

These small language changes (grouped under a project named Coin):

Strings in switch

Automatic resource management in try-statement

Improved type inference for generic instance creation, aka the diamond operator <>

Simplified varargs method declaration

Binary integer literals

Allowing underscores in numeric literals

Catching multiple exception types and rethrowing exceptions with improved type checking

Concurrency utilities under JSR 166

New file I/O library to enhance platform independence and add support for metadata and symbolic links. The new packages are java.nio.file and java.nio.file.attribute

Timsort is used to sort collections and arrays of objects instead of merge sort

Library-level support for elliptic curve cryptography algorithms

An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs

New platform APIs for the graphics features originally implemented in version 6u10 as unsupported APIs

Enhanced library-level support for new network protocols, including SCTP and Sockets Direct Protocol

Upstream updates to XML and Unicode
Lambda (Java's implementation of lambda functions), Jigsaw (Java's implementation of modules), and part of Coin were dropped from Java 7, and released as part of Java 8 (except for Jigsaw, which will be in Java 9).


From April 2012, Java 7 has been the default version to download on java.com.





Monday, 5 January 2015