Posts

Showing posts with the label Java

Immutability in java

In Java, Object can be of two types :- Mutable Immutable Mutable objects are the ones whose state can be changes during its lifetime. This is in contrast with Immutable objects , whose state cannot be changed once created. We have many classes in Java which provide immutable objects like String, Integer etc. In this post, I will discuss the immutability in detail, with its features and where can we use this. In basic terms, Immutable objects are the ones, whose state cannot be changed.e.g Integer i = new Integer(10) ; The Integer class provides us no method which can change the state/value of i. So we say Integer is an immutable class & object i is an immutable object. We have many benefits for it: - They are good candidates to cache :- Since immutable objects do not change their state, we can share or cache them and retrieve them in future, without copying and cloning the object. Solid keys :- Immutable objects makes the best keys for Hash classes. HashCode() ...

Generate Heap Dump in Unix

Image
Heap dump provides the insight into the JVM - shows live objects on the heap (reachable and unreachable) along with their types and values. In addition it also provides no of objects and their size as %age of total heap size.We have many ways to get the heap dump in Windows. Some are as follows:- jconsole jVisual VM Eclipse MAT ....and it goes on Out of above , i like jVisualVM the most due to its monitoring capability, interactive display, and easy to use. But the problem comes with the unix. Even though we can monitor the application remotely  but we cannot see the live objects, their size and number i.e we cannot get the heap dump remotely. To get the heap dump on Unix machine, we can use j map.  To use jmap , we need the process id of java application. At times, we have lot many java process running in unix and its difficult to identify. Java provides jps tool which list the JVM with the process Id which it got the...

Why Time gets truncated with ResutSet getDate() function.

Recently I stuck in an issue on populating date from stored procedure. I am reading a date from a resultset using rs.getDate(), storing in a java.util.Date instance variable and displaying on the screen. Java.util.Date  mydate = rs.getDate(1); Output is only date while time is truncated.  But why …! That confused me a lot. So I google it. Spending lot of time in reading blogs, oracle docs and trying different things on oracle server like checking  NLS_DATE_FORMAT, I am not able to get the time. Next I come across a Timestamp thing in Resultset class. Rs.getTimestamp (int colIndex) When I use it, I immediately get the time.  Now, the important question, why the resultset function getDate() does not return the Time. Now my search is preety narrow. What I found is :- In java, we have java.util.Date for java.sq.Date . So functionalities available in sql.Date are also available in util.Date. But there is one difference, sql.Date stores only Date and not Time ...

Where to declare Constants in Java

Its been an topic of debate where should constants be declared. Let look at approaches :- Declared in an Interface. Declared in a Class. Enums Going through google, i found number of explanation for both of these. Each have their pros and cons. I'll try to summarise and share my thoughts on it. Lets start with interface . In Java, Interfaces are used as abstract type, that contain method signatures, constants and nested types as  according to Oracle . We can use interfaces to defined a contract or for communication  as explained in my previous article . If we define constants here, we can have the following consequences:- We cannot stop a class to not implement an interface.So a Global constant interface can be used for subtype which is not advisable. We cannot give define constants depend on certain state condition. All the constants would stay in memory all the time. Although, we can define constants in interfaces, we have the above constraints. Lets...

More About Java Arrays

With the addition of Collections in Java, the use of primitives and primitive arrays decreases day by day. But at the API level or framework design level, primitives are highly used even today as they are fast and does’t include method chaining.  Arrays class in Java, provides the basic to advanced functionality to arrays. Java 6 adds a couple of more functions to this class. They are   copyOf ( T[ ] original, int newLength  ) copyOfRange( int[ ] original, int from, int to  )  CopyOf copies the array and allows to explicitly defined the size of new array, padding with zeroes (in case of int, float, double, short), null (in case of char) and false (in case of boolean). Its similar to System.arraycopy() but  doesnt allows to specify the size of output array. Simple but useful functionality.   Lets understand with the example:- public class Test { public static void main(String[] args) { int[] orig={1,2...

Learning JDK 7 Features Part 3: Try With Resource

Today we follow some standard coding conventions so that code should easy to read and maintainable or   i can say " Code should look beautiful  ". But there are some cases where we find our code is cluttered or duplicated. Its more often with Exception Handlers , Streams and JDBC  calls i.e. opening and closing streams/connections and multiple catch handlers. Java 7 comes to rescue us from this duplication and is succeeded in it. Before Java 7, to cloase a resource, we write a final block and close every resource in it. but some times the finally block become large and cluttered. Take a look at the code below:- finally { try { if (resultSet != null) resultSet.close(); } catch(Exception e) {} finally { try { if (statement != null) statement.close(); } ...

Why java supports Multiple Interface Inheritance

Java does not support multiple class inheritance i.e. we cannot extend multiple classes at one time in a class. But we can implememt multiple interfaces in a class. Lets start with the benefits of inheritance. Interfaces are user for two reasons :- 1) Contract 2) Communication Contract ,is an aggrement between the interface and the implementing class, that the class will provide the implementation of the methods of the interface's. On has to adhere to the contract. Collections in java has many interfaces like Set, List, Map. These interfaces provide the basic set of methods for the class depending on its interface type.We have their implementation classes like HashSet for Set, ArrayList for List and HashMap for Map. Communication , is used to communicate certain functionality of a class to the outside world. This is very usefull when you want to expose a class but we dont want that one should know all the methods , variables and other class informa...

Fix double check locking in Java 5

We can fix the double check locking  using volatile keyword. In Java 5, the JRE system will not allow a write of volatile to be reordered i.e read and write of volatile cannot be reordered w.r.t any previous read and write. So the volatile always gives the latest value. class Foo{ private volatile Helper helper=null; public Helper getHelper(){ if(helper=null){ synchronized(this){ if(helper=null) helper=new Helper(); } } return helper; } }

Learning JDK 7 Features Part 2: Updated Generic Instance Creation

Prior to Java 7, we create the generic instance as follows:- List<String> list = new ArrayList<String>( ); This syntex tunrs urgly in complex situations in which the length of type parameters increases. As mentioned in Effective Java (2nd Edition) chapter 2 , Joshua suggest us a way which can reduce the verbosity of generic instance creation; as follows public class TypeInference {                public static void main(String[ ] args)                     {                       List list = TypeInference.newInstance(); list.add("str");                     }        ...

Learning JDK 7 Features Part 1 : Strings in switch Statements

Switch statement is enhanced in JDK 7 with the support of String Object. Prior to it JDK 7 release, switch only supports  byte , short , char , and int   litearls. With this release onwards, we use string objects in switch expressions. Its is same as comparing String.equals method for each case. Please note the comparison is CASE- SENSITIVE.   Let see how it works :- private static String getTypeOfSeasonFromSwitch(String monthArg) { String typeOfSeason = null; switch (monthArg) { case "December": case "January": case "Febuary": typeOfSeason = "Winter"; break; case "March": case "April": case "May": typeOfSeason = "Spring"; break; case "June": case "July": case "August": typeOfSeason = "Summer"; b...

Generate Java POJO and Hibernate XML from database tables

Today we have frameworks to persist java objects to database without writing DAO's and hibernate is one which is widely used. But for nascent developers, creating its mapping to database tables is still difficult. Recently I come across a way to generate Java  POJO and hibernate mapping XML  from database tables  using a Jboss Hibernate Tools. Its as easy as a click  and magic, mapping XML is generated and corresponding POJO 's are generated. Listed down the steps :- 1. Install the hibernate-tools jar using Eclipse's Install New software, selecting URL from http://www.jboss.org/tools/download.html depending upon the eclipse version. 2. Click on [File -> New -> Other -> Hibernate -> Hibernate Configuration File] and create a cfg file. The following properties should be specified : jdbc url , username, password, DB schema, driver class and dialect. 3. Click on [File -> New -> Other -> Hibernate -> Hibernate Console Configuration ] and crea...