Tuesday, August 30, 2011

How to use string in switch case in Jdk 7 with example

Have you ever feel that String should be used in switch cases as like int and char? JDK 7 has made an important enhancement in there support of String, now you can use String in switch and case statement, No doubt String is most widely used type in Java and in my opinion they should have made this enhancement long back when they provided support for enum in java and allowed enum to be used in switch statement. In this java tutorial we will see how we can use String inside switch and case statement in JDK 7. This article is in continuation of my earlier post on JDK7 feature improved exception handling using multi cache block in Java

string and switch in jdk7 example tutorial many a times we want to switch based upon string output received from user or other part of program but before JDK7 we can't do it directly instead either we need to map those String to final integer constant or char constant to use them inside switch and case or you need to fallback on if-else statement which gets clumsy once number of cases getting increased. But now with jdk7 you can directly use String inside switch and case statement. Though it’s pretty straight forward feature let see an example of how to use String inside switch and case statement in JDK7.

Example of String in Switch in JDK7


public static void tradingOptionChooser(String trading) {
 switch (trading) {
  case "Stock Trading":
       System.out.println("Trader has selected Stock Trading option");
       break;
  case "Electronic Trading":
       System.out.println("Trader has selected Electronic Trading option");
       break;
  case "Algorithmic Trading":
       System.out.println("Trader has selected Algorithmic Trading option");
       break;
  case "Foreign exchange trading":
       System.out.println("Trader has selected Foreign exchange Trading option");
       break;
  case "commodity trading":
       System.out.println("Trader has selected commodity trading option");
       break;
 default:
       throw new IllegalArgumentException();
 }
}

Example of String in Switch prior JDK7

Now let's see how it can be done prior to JDK 7 using if-else statement:
public static void tradingOptions(String trading) {

if (trading.equals("Stock Trading")) {
System.out.println("Trader has selected Stock Trading option");

} else if (trading.equals("Electronic Trading")) {
System.out.println("Trader has selected Electronic Trading option");

} else if (trading.equals("Algorithmic Trading")) {
System.out.println("Trader has selected Algorithmic Trading option");

} else if (trading.equals("Foreign exchange trading")) {
System.out.println("Trader has selected Foreign exchange Trading option");

} else if (trading.equals("commodity trading")) {
System.out.println("Trader has selected commodity trading option");

} else {
throw new IllegalArgumentException();
}
}

Overall allowing String into switch and case statement is not a wow feature but in my opinion very useful one and definitely makes coding easier and make code more readable by either removing clumsy if-else statement. So I definitely vote plus one to JDK 7 String in switch feature and thanks to guys involved in project coin for making life easier of java developers.

You also need to ensure that your JRE must have source 1.7 otherwise if you try to run string in switch in JRE less than 7 you will get following errro

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - strings in switch are not supported in -source 1.6
  (use -source 7 or higher to enable strings in switch)
        at jdk7demo.JDK7Demo.tradingOptionChooser(JDK7Demo.java:34)
        at jdk7demo.JDK7Demo.main(JDK7Demo.java:25)


That’s all from me on String and Switch on JDK7, Please share how you are using this new feature of java 7.

Here are some of my other post on Java you may find interesting:

Saturday, August 27, 2011

Why Java does not support Operator overloading

Unlike C++, Java doesn't support operator overloading. Java doesn't provide freedom to programmer, to overload the standard arithmetic operators e.g. +, -, * and / etc. If you have worked previously in C++, than you know that, Java has left lot of feature supported in C++ e.g.  Java doesn't support multiple inheritance, no pointers in Java, and no pass by reference in Java. Rarely this question asked in Java interviews, to check how programmer thinks about certain features, which is not supported in Java. Another similar questions is regarding Java being pass by reference, which is mostly appear as, whether Java is pass by value or reference. Though I don't know the real reason behind it, I think following observation make sense on, why Operator overloading is not supported in Java.


1) Simplicity and Cleanliness
Why operator overloading is not supported in JavaSimple and clear design was one of the goals of Java designers. They, just don't want to replicate the language, but wanted to have a clear, truly object oriented language. Adding Operator overloading would have definitely made design more complex than without it, and it might have lead to more complex compiler or slows the JVM ,because it needs to do extra work to identify the actual meaning of operators, and reduce the opportunity to optimize the language by guarantee behavior of operators in Java.

2) Avoid Programming Errors
Java doesn't allow user defined operator overloading, because if you allow programmer to do operator overloading, they will come up with multiple meanings for same operator, which will make the learning curve of any developer hard and things more confusing and messy. Its been observed that, there is increase in programming errors, when language supports operator overloading, which in turn increase e development and delivery time. Since Java and JVM has taken most of developers responsibility,  in memory management by providing garbage collector, it doesn't really make sense to left this feature to pollute the code, and as a loop hole for programming errors.

3) JVM Complexity
From JVM perspective, supporting operator overloading is more difficult, and if the same thing can be achieved, by using method overloading in more intuitive and clean way, it does make sense to not support operator overloading in Java. A complex JVM, may result in slower JVM, than a relatively simpler JVM ,and reduce the opportunity of optimization by taking out guaranteed behavior of operators in Java.

4) Easy Development of Tools
This is an additional benefit of not supporting operator overloading in Java. Omission of operator overloading has kept the language easier to handle and process, which in turn makes it easier to develop the tools, that process the language e.g. IDE or re-factoring tool. Re-factoring tools in Java are far better than C++.

In conclusion many things, which can be achieved by operator overloading, can also be achieved using method overloading using more intuitive and easy way and that might be the reason java designer thought that supporting operator overloading will not be a big benefit for language, but in fact only Java designer can answer real motivation of, why Java doesn't support operator overloading, like some other questions as Why Java doesn't support multiple inheritance or Why String is immutable in Java.

Friday, August 26, 2011

5 example of sort command in UNIX or Linux >>>> Unix Tutorial

Sorting is one of essential task we always need to perform and UNIX or Linux has great support for sorting by using sort command. No matter what kind of shell script you are writing or you are looking for some information or reports many times you need to sort the output from one command or a set of line, with combination of sort with find command and grep in unix you can handle support request and reporting quite easily. In this UNIX sort command tutorial we will see how we can use sort command in UNIX to achieve our sorting goal. This tutorial contains some of practical example of sort command for sorting data in UNIX. With the use of “uniq” and “sort” command you can remove duplicates and present a sorted data in UNIX.

Saturday, August 20, 2011

How to resolve java.lang.ClassNotFoundException in Java

What is ClassNotFoundException in Java
ClassNotFoundException is one of Java nightmare every Java developer face in there day to day life. java.lang.NoClassDefFoundError and java.lang.ClassNotFoundException are two errors  which occurs by and now and chew up of your precious time while finding and fixing root cause. From the name java.lang.ClassNotFoundException looks quite simple but underlying cause of it is always different and which classifies it as an environmental issue. In this java tutorial we will see what is ClassNotFoundException in java, what is real cause of it and how to fix it along with some more frequent and infamous examples of java.lang.ClassNotFoundException in Java or J2EE, Don’t mistake this exception with NoClassDefFoundError in Java which is also due to incorrect classpath in Java.  Though both of them are related to missing class file when Java tries to load class in Java they are completely different to each other.  Correct understanding of  When class is loaded in Java and How Classpath works  is must to troubleshoot and fix this error quickly.

Friday, August 19, 2011

10 Best Practices to Follow while writing Code Comments

Comments are an important part of writing code not only in Java, but whatever programming or scripting language you use. At the same time this is one of the most abused things as well. Both writing no comment and writing too much comment is bad and this has been high lighted by many software gurus e.g. Robert C. Martin in his classic book Clean code. There is a whole chapter dedicated on How to write comments and finding pros and cos of comment. This article is my learning in same direction, here I am going to share with you guys some 0f the rule and best practices I follow while writing comments. Before that let's first see what is the purpose of having comment in the code? Why do we need comment, isn't writing code is enough. Some of the people I have met always argue that we are getting paid for writing code and not comment :).

code comments best practices in javaAnyway in my opinion we all agree with each other that software spend only 10% time of its life in development and rest of 90% in maintenance. This 90% part of maintaining the code is where comment can help you immensely. Since no single developer stays till whole life of any product or software and its often new people, who works of already written code. These are the people who read the code and not aware of why a certain piece of code has been written, here comments can help them to understand code quickly and believe me you will get lot of roses from that fellow developer :). 

Anyway long story short here are some of the things I try to follow while writing code:

10 tips on writing code comments

1) Focus on readability of code; assume that you don't have comments to explain the code. Give your method, variables and class meaningful name.

2) Don't write what code is doing, this should be left for the code to explain and can be easily done by giving class, variable and method meaningful name. For example:

//calculates square root of given number 
//using Newton-Raphson method
public void abc(int a){
       r = a / 2;
       while ( abs( r - (a/r) ) > t ) {
       r = 0.5 * ( r + (a/r) );
       }
       System.out.println( "r = " + r );
}
 
Above code is calculating square root using Newton-Raphson method and instead of writing comment you can just rename your method and variable as follows:

public void squareRoot(int num){
       root = num/ 2;
       while ( abs(root - (num/ root) ) > t ) {
       r = 0.5 * (root + (num/ root));
       }
       System.out.println( " root = " + root );
}
 
3) Always write why you are writing this piece of code, why you are writing this piece of code because this information is not visible until you write them in comments and this is critical to identify any bug or behavior with changing business environment.

4) If you are writing core libraries which will be used by different project and with different teams. Follow javadoc comment style and document all assumption and precondition for using your API. Joshua Bloch has also mentioned about writing Java-doc comment in his classic Effective Java, which is worth knowing.

5) Include JIRA Number and description on comment, especially if you are modifying an existing piece of code as part of maintenance. This I found extremely useful while comparing different version of code in CVS or SVN. This gives you clear idea why that particular code has been added and whether issue is because of that piece of code or not.


6) Always try to finish your comment in as few words as possible, one liner comment is best until its explaining "Why" part and can't be replaced by code itself. No body likes or has enough time to read longer comment.

7) Don't write story in comment as your name, employee id, your department etc because those information can be obtained from CVS commit data in case someone wants to know who has make this change.

8) Always put comment while committing code in source control repository and especially why you are adding this piece of code if possible include JIRA or QC Number so that any one can refer JIRA for complete details.

9) If you want upcoming developer to follow certain standards or inform about certain things then include them in the beginning of your class as comment. E.g. suppose if you are writing serializable class in java then its good to put a serializable alert stating that any new fields addition in this class must implement serializable interface in java or make it transient etc.


10) Last but not the least give your code to fellow developer to understand as part of code review and ask him how much he understands it.

That’s all from me on code commenting, please share the standard, best practices or your experience with writing comments on code. I believe these are the areas which a junior developer or even we can improve and it’s only possible from learning which each mother's experience.
Happy weekend :)

What is polymorphism in Java? Method overloading or overriding?

What is Polymorphism in Java
Polymorphism is an important Object oriented concept and widely used in Java and other programming language.  Polymorphism in java is supported along with other concept like Abstraction, Encapsulation and Inheritance. Few words on historical side; Polymorphism word comes from ancient Greek where poly means many so polymorphic are something which can take many form. In this Java Polymorphism tutorial we will see what is Polymorphism in Java , How Polymorphism is implemented in Java e.g method overloading and overriding, why should we use Polymorphism and how can we take advantage of polymorphism while writing code in Java. Along the way we will also see a real world example of using Polymorphism in Java

Saturday, August 13, 2011

Java Enum Tutorial: 10 Examples of Enum in Java

What is Enum in Java
Enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java, For example Number of days in Week, Number of planets in Solar system etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing , Generics, varargs and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically. By the way, Java Enum as type is more suitable to represent well known fixed set of things and state,  for example representing state of Order as NEW, PARTIAL FILL, FILL or CLOSED. Enumeration(Enum) was not originally available in Java though it was available in other language like C and C++ but eventually Java realized and introduced Enum on JDK 5 (Tiger) by keyword Enum. In this Java Enum tutorial we will see different Enum example in Java and learn using Enum in Java. Focus of this Java Enum tutorial will be on different features provided by Enum in Java and how to use them. If you have used Enumeration before in C or C++ than you will not be uncomfortable with Java Enum but in my opinion Enum in Java is more rich and versatile than in any other language. . By the way, if you like to learn new concepts using book than you can also see Java 5.0 Tiger : A Developers notebook, I had followed this book while learning Enum, when Java 1.5 was first launched. This book has excellent chapter not only on Enum but also on key features of Java 1.5 and  worth reading.

Friday, August 12, 2011

How to view Javadoc in Netbeans IDE 7.0

Recently I have downloaded Netbeans IDE 7.0 to learn its GUI builder Matisse and I was impressed with the changes I saw in the Netbeans from  my last use of it on 2007. I was a hardcore Netbeans fan when I was developing mobile application using J2ME and Netbeans integrated environment with WTK, Profiler and Network Monitor just rocks and on top of that they had conditional compilation feature based on type of platform you   were working like you could maintain your code easily even if you are using device specific libraries e.g. Nokia UI library etc. Anyway those were the things of past, what attracted me is the Javadoc feature of Netbeans. Though this feature might have been existed long back I have just started using it. Earlier to see javadoc I used to Google and then go to Sun (now Oracle) website to view javadoc of any class. While playing with Netbeans I discovered that you can easily javadoc in the Netbeans IDE itself no need to visit the web.



There are multiple ways to see javadocs in Netbeans:

1) Select any java class and right click you will see an option "Show Javadoc" which will open the javadoc in brower. You can also use keyboard   shortcut "alt+F1" to do this fast. You can also learn my favorite eclipse keyboard shortcut here.



2) By using JavaDoc Index Search: javadoc index search is another cool feature provided by Netbeans IDE which is allowed to search for any Java class  or interface or anything and display the result in same window. To open javadoc index search window go to Help -->Java Doc Index Search option or press keyboard shortcut "Shift + F1"



3) By opening Javadoc window in Netbeans:  to open javadoc window in Netbeans go to Window-->Others-->Javadoc and this will open javadoc window which is perfect way of seeing java doc along with writing code. Another cool feature of this javadoc window is you just need to focus on any java class an it will automatically show the javadoc for that class. It also provides buttons to move back and forward for easy navigation and best is yet to say you can open the source file of that java class right in front of you by click button "Open Source in editor" simply awesome isn't it.

Though I have been using Eclipse from past few years I must say some of Netbeans IDE feature are simply great. One of them is there Swing GUI builder and the other one I like is there javadoc integration in IDE.

On side note Javadoc just comes integrated to me because I have downloaded JDK1.6+ Netbeans 7 bundle but in case you want to add javadoc for some other API or platform you can easily do this by following below Steps

Adding Javadoc in Netbeans IDE

  1. Go to Tools-->Java Platform It will open Java platform manager.
  2. Select the java platform for which you want to add javadoc could be J2ME also.
  3. Click on Javadoc tab and then just click the button Add Zip/Folder, point out your already downloaded javadoc and you are done.
That’s all on Javadoc and Netbeans IDE for now. Enjoy.

Related post: 


Monday, August 8, 2011

Java swing tutorial: Learning JList with code example

In this java swing JList tutorial we will learn important properties and function of JList while working on task with examples. In my opinion best way to learn swing is to actually doing task and so I designed this tutorial around task. We will start with simple example and proceed with more  complex one step by step adding new functionality and in the course we will learn JList both concept and API. In this first example we need to implement a list which shows names of companies in sorted order. Before start coding let's see some fundamentals of JList:

1) JList is a GUI element available in javax.swing package which allows selection of one more element. Internally JList is backed up by two models: ListModel for holding data and ListSelectionModel for handling selection. JList also allows custom rendering via ListCellRenderer which can be used to draw a specific cell in customize manner.


2) JList elements are uneditable, JList does not support any rendering.


3) There are two ways to set model of JList either using JList.setModel() or JList.setListData().


4) JList implements Scrollable interface and can be put on Scrollpane. JList also supports auto-scrolling. visibleRowCount property of JList is used to display number of rows when a JList is placed on Scrollpane.you can change it by using method setVisibleRowCount().


5) JList cell's width and height is determined by width of widest element and height of highest element but you can also customize it using methods setFixedCellWidh() and setFixedCellHeight().




JList example in Java Swing

Task: Implement JList which display list of electronic trading in sorted ascending order.


Let's see an example of dispalying JList in Swing:


Showing JList in Swing is very easy what you need to do is: create a JList, set its model, put the JList in Panel and done. For creating model for JList you can extend AbstractListModel class which implements ListModel and you can store your data inside this class in either Array or Collection classes as shown in below example of JList:

public class JListCodeDemo {

      public static void main(String args[]){
      JFrame listFrame = new JFrame();
      JPanel contentPane = (JPanel) listFrame.getContentPane();
      JList list = new JList(new AbstractListModel() {

      String[] companies = {"Stock trading", "Futures trading", "Options trading"};
      @Override
      public int getSize() {
      return companies.length;
      }

      @Override
      public Object getElementAt(int index) {
      return companies[index];
      }
      });
      contentPane.add(list);
      listFrame.pack();
      listFrame.setVisible(true);
      listFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      }
}


Now to display elements in Sorted Order we need to sort the data which we are going to show in JList. For this purpose we will create our own custom ListModel and store our data in List and then sort this list using Collections.sort() method which will sort Strings on there natural order. Here is the code:

class ElectronicTradingListModel extends AbstractListModel{

      private List electronic_trading_list = new ArrayList();

      public ElectronicTradingListModel(){
      electronic_trading_list.add("Equity Trading");
      electronic_trading_list.add("Futures Trading");
      electronic_trading_list.add("Options Trading");
      electronic_trading_list.add("Currency trading");
      Collections.sort(electronic_trading_list);

      }

      @Override
      public int getSize() {
      return electronic_trading_list.size();
      }

      @Override
      public Object getElementAt(int index) {
      return electronic_trading_list.get(index);
      }

}


Now just set this model as your list model by adding following line of code:


list.setModel(new ElectronicTradingListModel());


Let me know how you find this example of JList in Swing, how is my idea of having task based tutorial. To be frank I really liked this thought because it provides you a focus which is quite important otherwise you will lose in this huge API. So focus here is to learn fundamentals of JList and Swing by doing actual real world task. In the next JList tutorial we will see how to implement custom rendering on JList by our next task: Display currency trading in yellow color and Stock trading on red color


Here are some of my favorite java tutorial you may find interesting

Saturday, August 6, 2011

How to Convert String to Integer to String in Java with Example

Converting String to integer and Integer to String is one of the basic tasks of Java and most people learned about it when they learn Java programming. Even though String to integer and Integer to String conversion is basic stuff but same time its most useful also because of its frequent need given that String and Integer are two most widely used type in all sort of program and you often gets data between any of these format. One of the common task of programming is converting one data type another e.g. Converting Enum to String or Converting Double to String, Which are similar to converting String to Integer. Some programmer asked question that why not Autoboxing can be used to Convert String to int primitive or Integer Object? Remember autoboxing only converts primitive to Object it doesn't convert one data type to other. Few days back I had to convert a binary String into integer number and then I thought about this post to document all the way I know to convert Integer to String Object and String to Integer object. Here is my way of converting String to Integer in Java with example :

Wednesday, August 3, 2011

How to increase java heap space on Maven and ANT

Many times we get java.lang.OutOfMemoryError: java heap space while building our project either by using maven or ANT just because heap size is not enough to build the project. At this point we just want to increase the heap size used by ANT or MAVEN and this java tip will let you do this:

How to increase Java Heap size for Maven on Linux/Unix

1. Open your mvn.sh file and add the following line:
export MAVEN_OPTS=-Xmx512m
this will allow to specify java heap space based on your project needs.