spring MVC

Sunday, 12 October 2014

Why String is immutable or final in Java

Why String is immutable or final in Java

This is one of the most popular String Interview questions in Java, which starts with discussion of,  What is String, How String in Java is different than String in C and C++, and then shifted towards what is immutable object in Java , what are the benefits of immutable object , why do you use it and which scenarios do you use it. This is some time also asked as "Why String is final in Java" . Though there could be many possible answer for this question, and only designer of String class can answer this , I think below two does make sense

1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  This one is also suggested by  Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"


Security and String pool being primary reason of making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post. By the way, above reason holds good to answer, another Java interview questions "Why String is final in Java".  Also to be immutable you have to be final, so that your subclass doesn't break immutability.  what do you guys think ?


Top 5 Java Programming Books

Top 5 Java Programming Books -  Must Read

These top Java programming books are very good Java books and I would say best of lot. Whenever a programmer starts learning Java first question he ask is "Which Java books should I refer for learning?", That itself says, how important Java books are for programmers. Despite so much free resource available in Java in terms of tutorials, tips, blogs and code example, Java books has there own place because of two reason :

1) They are written by programmers who are authority in subject
2)They cover the subject with more details and explanation.

These Java books are my personal favourites and whenever I get some time I prefer to read them, though I have read many of them already, I always learn something new when I read them again. They are kind of best Java books available today.


1) Head First Java
Best Java Programming Books Head FirstHead First Java is the best Java book for any programmer who are new in both programming and Java. The head first way of explanation is quite a phenomena and I really enjoyed whenever I read there books. I found them most interesting Java programming books for beginners but they are equally good for intermediate as well. Head first Java covers essential Java programming knowledge about class, object, Thread, Collection, language feature like Generics, Enum, variable arguments or autoboxing etc. They also has some advanced section on Swing, networking and Java IO which makes them complete package for Java beginners. This should be your first Java book if you are learning from scratch. 






2) Head First Design Pattern
Head First Design Pattern is another top class Java book from Head First lab, I guess, this is so far there best title. When I started reading this book back in 2006, I didn't much about design patterns in Java , how they solve common problems, how to apply design pattern, what benefits they provide and all sort of basic things but after reading this Java book I benefited immensely. There is first chapter on Inheritance and Composition, which is simply fantastic and promote best practices by first introducing problem and then solution. They also have lots of bullet points, exercises, memory maps which help you to understand design patterns much quickly. If you want to learn core Java design patterns and Object oriented design principle, this is the first Java book you should refer. Head First design pattern is written by Kathy Sierra and team.



3) Effective Java
Effective Java is one of the best or top Java books in my record and most enjoyable as well. I have high regards for Joshua Bloch (writer of this book) for his contribution in Java collection framework and Java concurrency package. Effective Java is best for seasoned or experienced programmer who are well versed in Java programming and want to sharp there skill by following programming best practices, Java best practices and eager to listen from someone who is contributed in Java development kit. Effective Java as book scores high on quality, content and way of explanation. Reading this Java book is pleasant experience. Another important point of Effective Java is Item based structure which breaks whole book in small items and every Item is complete in itself, so you can read this book while travelling or short duration as well. On contents Effective Java is collection of Java programming best practices ranging from static factories, serialization,  equals and hashcode to generics, enum and varargs and reflection. This Java programming book almost cover every aspect of Java in slightly different way then you are used to.  



4) Concurrency Practice in Java
Java Concurrency in Practice is another classic from Joshua Bloch, Doug Lea and team. Probably the best Java book in Concurrency and multi-threading and one of the must read for core Java developers. Strength of Concurrency Practice in Java are
1) This book is very detailed and capture minor details of multi-threading and concurrency as well.
2) Focus, instead of focusing on core Java classes this book focus on concurrency issues and problems like deadlock, starvation, thread-safety, race conditions and then present ways to solve them using Java concurrency classes. This book is excellent resource to learn and master Java concurrency package and classes  like CountDownLatchCyclicBarrier,BlockingQueue or Semaphore. This is the biggest reason I like to read this Java book and read again and again.
3) One more strong point of Concurrency practice in Java is No nonsense Examples, examples in this book are clear, concise and intelligent
4) Explanation : book is good on explaining what is wrong and why its wrong and how to make it right which is essential for Java book to succeed.





5) Java Generics and Collections
Java Generics and Collection by Naftalin and Philip Wadler from O'Reilly is another great book on Java, which I initially forgot to include in my list, but including it now as requested by many readers. I personally like this book because of its content of Generics and Collections, which is core areas of Java programming language. Strong knowledge of  Java Collections and Generics are expected from any experienced programmer and this books help on that area. It explains each of Collection interface e.g. Set, List, Map, Queue and there implementation and compares how well they perform in different situation. I really loved there comparison chart at the end of each chapter. 



6)Java performance from Binu John
Another good Java book which is my personal favourite. As we are moving gradually started from beginners level to intermediate and senior level. Java performance Book is all about performance monitoring, profiling and tools used for Java performance monitoring. This is another, must read Java book, if you are serious about performance in Java programming language. This is not a usual programming book, Instead It provides details about JVMGarbage CollectionJava heap monitoring and profiling application. I lover there chapter on JVM overview and its must read to learn about JVM in simple language. Just remember this Java book is advanced in nature and expect that reader has experience in Java. Beginners and intermediate programmer can also benefit from this book but Its good to have some Java experience on your belt before reading this book. So far best Java book on performance monitoring.




7) Java Puzzlers
Java Puzzlers is another worth reading Java book from Joshua Bloch, this time with Neal Gafter. This book is about corner cases and pitfalls in Java programming language. Java is more safe and secure than C++ and JVM does good job to free programmer from error-prone memory allocation and deallocation, but still there Java has corner-cases which can surprise even experienced Java programmer. This Java books presents such Java pitfalls and explains them in detail. A good Java book if you love puzzles, You can even include many of these in core Java interviews to check how deep there Java knowledge is. I don't rate it as high as Effective Java and Concurrency Practice in Java but still you can give it a go. In order to get most of this Java book, tries to solve the puzzles by yourself and then look into explanations to make your knowledge more concrete. 




8) Head First Object Oriented Analysis and Design
Another good book on Java programming and design principles from Head First series. Head first Object Oriented Analysis and design book can be read in conjunction with Head First Design patterns. This book focus on Object oriented design principles like favour composition over inheritance, programming for interface than implementation, DRY etc. One part of learning Java is writing good code and following best practices and this book is great in educating programmers about them. knowledge gained from this book is applicable to many object oriented programming language and will overall improve your understanding of code and design principles. 







9) Thinking in Java
Thinking in Java book is written by Bruce Eckel who is also author of Thinking in C++ and he uses his unique style to teach Java concept. Many would agree that this is one of the best Java book and strength of this books are there to the point and intelligent examples. This is one of the complete book in Java and can be used as reference as well. There is a chapter on Java memory mapped IO from Thinking in Java which is my favourite. I would say this is another Java book which demands space in Java programmer's shelf and must read Java book for beginners, especially if you don't like Head First teaching style and rather need a beginners Java book with plain old example style, Thinking in Java is a good choice. It is detailed, matured and frequently updated.





This was my list of Top Java programming books and I would say best of lot. I have read all the books, some of them I am still reading and couple of them like Effective Java and Head First series, I have read couple of times. Many programmer ask me about which books they start, which Java book they read now. I hope you will find some good Java books in this collection.

10 Object Oriented Design Principles Java Programmer should know

10 Object Oriented Design Principles Java Programmer should know

Object Oriented Design Principles are core of OOPS programming, but I have seen most of Java programmer chasing design patterns like Singleton pattern , Decorator pattern or Observer pattern , and not putting enough attention on learning Object oriented analysis and design. It's important to learn basics of Object oriented programming like Abstraction, Encapsulation, Polymorphism and Inheritance, but same time, it's equally important to know these design principles, to create clean and modular design. I have regularly seen Java programmers and developers of various experience level, who either doesn't heard about these OOPS and SOLID design principle, or simply doesn't know what benefits a particular design principle offers, or how to use these design principle in coding.

Bottom line is, always strive for highly cohesive and loosely couple solution, code or design. Looking open source code from Apache and Sun are good examples of learning Java and OOPS design principles. They show us,  how design principles should be used in coding and Java programs. Java Development Kit follows several design principle like Factory Pattern inBorderFactory class,  Singleton pattern in Runtime class, Decorator pattern on various java.io classes. By the way if you really interested more on Java coding practices,  read Effective Java by Joshua Bloch , a gem by the guy who wrote Java API. My another personal favorite on object oriented design pattern is,  Head First Design Pattern by Kathy Sierra and others and Head First Object Oriented Analysis and Design . These books helps a lot to write better code, taking full advantage of various Object oriented and SOLID design principles.


Object oriented design principles and pattern in Java programmingThough best way of learning any design principle or pattern is real world example and understanding the consequences of violating that design principle, subject of this article is Introducing Object oriented design principles for Java Programmers, who are either not exposed to it or in learning phase. I personally think each of these OOPS and SOLID design principle need an article to explain them clearly, and I will definitely try to do that here, but for now just get yourself ready for quick bike ride on design principle town :)

DRY (Don't repeat yourself)

Our first object oriented design principle is DRY, as name suggest DRY (don't repeat yourself) means don't write duplicate code, instead use Abstraction to abstract common things in one place. If you have block of code in more than two place consider making it a separate method, or if you use a hard-coded value more than one time make them public final constant. Benefit of this Object oriented design principle is in maintenance. It's important  not to abuse it, duplication is not for code, but for functionality . It means, if you used common code to validate OrderID and SSN it doesn’t mean they are same or they will remain same in future. By using common code for two different functionality or thing you closely couple them forever and when your OrderID changes its format , your SSN validation code will break. So beware of such coupling and just don’t combine anything which uses similar code but are not related.

Encapsulate What Changes
Only one thing is constant in software field and that is "Change", So encapsulate the code you expect or suspect to be changed in future. Benefit of this OOPS Design principle is that Its easy to test and maintain proper encapsulated code. If you are coding in Java then follow principle of making variable and methods private by default and increasing access step by step e.g. from private to protected and not public. Several of design pattern in Java uses Encapsulation, Factory design pattern is one example of Encapsulation which encapsulate object creation code and provides flexibility to introduce new product later with no impact on existing code.

Open Closed Design Principle
Classes, methods or functions should be Open for extension (new functionality) and Closed for modification. This is another beautiful SOLID design principle, which prevents some-one from changing already tried and tested code. Ideally if you are adding new functionality only than your code should be tested and that's the goal of Open Closed Design principle. By the way, Open Closed principle is "O" from SOLID acronym.

Single Responsibility Principle (SRP)
Single Responsibility Principle is another SOLID design principle, and represent  "S" on SOLID acronym. As per SRP, there should not be more than one reason for a class to change, or a class should always handle single functionality. If you put more than one functionality in one Class in Java  it introduce coupling between two functionality and even if you change one functionality there is chance you broke coupled functionality,  which require another round of testing to avoid any surprise on production environment.

Dependency Injection or Inversion principle
Don't ask for dependency it will be provided to you by framework. This has been very well implemented in Spring framework, beauty of this design principle is that any class which is injected by DI framework is easy to test with mock object and easier to maintain because object creation code is centralized in framework and client code is not littered with that.There are multiple ways to  implemented Dependency injection like using  byte code instrumentation which some AOP (Aspect Oriented programming) framework like AspectJ does or by using proxies just like used in Spring. See this example of IOC and DI design pattern to learn more about this SOLID design principle. It represent "D" on SOLID acronym.

Favor Composition over Inheritance
Always favor composition over inheritance ,if possible. Some of you may argue this, but I found that Composition is lot more flexible than Inheritance. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time. Even Effective Java advise to favor composition over inheritance.

Liskov Substitution Principle (LSP)
According to Liskov Substitution Principle, Subtypes must be substitutable for super type i.e. methods or functions which uses super class type must be able to work with object of sub class without any issue". LSP is closely related to Single responsibility principle and Interface Segregation Principle. If a class has more functionality than subclass might not support some of the functionality ,and does violated LSP. In order to follow LSP SOLID design principle, derived class or sub class must enhance functionality, but not reduce them. LSP represent  "L" on SOLID acronym.

Interface Segregation principle (ISP)
Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that. This happens mostly when one interface contains more than one functionality, and client only need one functionality and not other.Interface design is tricky job because once you release your interface you can not change it without breaking all implementation. Another benefit of this design principle in Java is, interface has disadvantage to implement all method before any class can use it so having single functionality means less method to implement.

Programming for Interface not implementation
Always program for interface and not for implementation this will lead to flexible code which can work with any new implementation of interface. So use interface type on variables, return types of method or argument type of methods in Java. This has been advised by many Java programmer including in Effective Java and head first design pattern book.

Delegation principle
Don't do all stuff  by yourself,  delegate it to respective class. Classical example of delegation design principle is equals() and hashCode() method in Java. In order to compare two object for equality we ask class itself to do comparison instead of Client class doing that check. Benefit of this design principle is no duplication of code and pretty easy to modify behavior.

All these object oriented design principle helps you write flexible and better code by striving high cohesion and low coupling. Theory is first step, but what is most important is to develop ability to find out when to apply these design principle. Find out, whether we are violating any design principle and compromising flexibility of code, but again as nothing is perfect in this world, don't always try to solve problem with design patterns and design principle they are mostly for large enterprise project which has longer maintenance cycle.


inheritance-vs-composition-in-java

Inheritance vs. Composition in Java

This article illustrates the concepts of inheritance vs. composition in Java. It first shows an example of inheritance, and then shows how to improve the inheritance design by using composition. How to choose between them is summarized at the end.
1. Inheritance
Let's suppose we have an Insect class. This class contains two methods: 1) move() and 2)attack().
class Insect {
 private int size;
 private String color;
 
 public Insect(int size, String color) {
  this.size = size;
  this.color = color;
 }
 
 public int getSize() {
  return size;
 }
 
 public void setSize(int size) {
  this.size = size;
 }
 
 public String getColor() {
  return color;
 }
 
 public void setColor(String color) {
  this.color = color;
 }
 
 public void move() {
  System.out.println("Move");
 }
 
 public void attack() {
  move(); //assuming an insect needs to move before attacking
  System.out.println("Attack");
 }
}
Now you want to define a Bee class, which is a type of Insect, but have different implementations ofattack() and move(). This can be done by using an inheritance design like the following:
class Bee extends Insect {
 public Bee(int size, String color) {
  super(size, color);
 }
 
 public void move() {
  System.out.println("Fly");
 }
 
 public void attack() {
  move();
  super.attack();
 }
}
public class InheritanceVSComposition {
 public static void main(String[] args) {
  Insect i = new Bee(1, "red");
  i.attack();
 }
}
The class hierarchy diagram is as simple as:
inheritance-vs-composition-1
Output:
Fly
Fly
Attack
"Fly" was printed twice, which indicates move() is called twice. But it should be called only ONCE.
The problem is caused by the super.attack() method. The attack() method of Insect invokesmove() method. When the subclass calls super.attack(), it also invokes the overridden move()method.
To fix the problem, we can:
  1. eliminate the subclass's attack() method. This will make the subclass depends on the superclass's implementation of attack(). If the attack() method in the superclass is changed later (which is out of your control), e.g., the superclass's attack() method use another method to move, the subclass will need to be changed too. This is bad encapsulation.
  2. rewrite the attack() method like the following:
    public void attack() {
     move();
     System.out.println("Attack");
    }
    This would guarantee the correct result, because the subclass is not dependent on the superclass any more. However, the code is the duplicate of the superclass. (Image attack() method does complex things other than just printing a string) This does not following software engineering rule of reusing.
This inheritance design is bad, because the subclass depends on the implementation details of its superclass. If the superclass changes, the subclass may break.
2. Composition
Instead of inheritance, composition can be used in this case. Let's first take a look at the composition solution.
The attack function is abstracted as an interface.
interface Attack {
 public void move();
 public void attack();
}
Different kinds of attack can be defined by implementing the Attack interface.
class AttackImpl implements Attack {
 private String move;
 private String attack;
 
 public AttackImpl(String move, String attack) {
  this.move = move;
  this.attack = attack;
 }
 
 @Override
 public void move() {
  System.out.println(move);
 }
 
 @Override
 public void attack() {
  move();
  System.out.println(attack);
 }
}
Since the attack function is extracted, Insect does not do anything related with attack any longer.
class Insect {
 private int size;
 private String color;
 
 public Insect(int size, String color) {
  this.size = size;
  this.color = color;
 }
 
 public int getSize() {
  return size;
 }
 
 public void setSize(int size) {
  this.size = size;
 }
 
 public String getColor() {
  return color;
 }
 
 public void setColor(String color) {
  this.color = color;
 }
}
Bee is a type of Insect, it can attack.
// This wrapper class wrap an Attack object
class Bee extends Insect implements Attack {
 private Attack attack;
 
 public Bee(int size, String color, Attack attack) {
  super(size, color);
  this.attack = attack;
 }
 
 public void move() {
  attack.move();
 }
 
 public void attack() {
  attack.attack();
 }
}
Class Diagram:
inheritance-vs-composition-2
public class InheritanceVSComposition2 {
 public static void main(String[] args) {
  Bee a = new Bee(1, "black", new AttackImpl("fly", "move"));
  a.attack();
 
  // if you need another implementation of move()
  // there is no need to change Insect, we can quickly use new method to attack
 
  Bee b = new Bee(1, "black", new AttackImpl("fly", "sting"));
  b.attack();
 }
}
fly
move
fly
sting
3. When to Use Which?
The following two items can guide the selection between inheritance and composition:
  1. If there is an IS-A relation, and a class wants to expose all the interface to another class, inheritance is likely to be preferred.
  2. If there is a HAS-A relationship, composition is preferred.
In summary, Inheritance and composition both have their uses, and it pays to understand their relative merits.