Friday, September 30, 2011

How to String Split Example in Java - Tutorial

Java String Split Example
I don't know how many times I need to Split String in Java. Split is very common operation given various data sources e.g CSV file which contains input string in form of large String separated by comma. Splitting is necessary and Java API has great support for it. Java provides two convenience methods to split strings first within the java.lang.String class itself: split (regex) and other in java.util.StringTokenizer. Both are capable to split the string by any delimiter provided to them. Since String is final in Java every split-ed String is a new String in Java.

Thursday, September 29, 2011

Top 10 Spring Interview Questions Answers J2EE

Spring framework interview questions is in rise on J2EE and core Java interviews,  As Spring is the best framework available for Java application development and now Spring IOC container and Spring MVC framework are used as de-facto framework for all new Java development. With this popularity interview questions from spring framework is top on any list of  core Java Interview questions. I thought to put together some spring interview questions and answers which has appeared on many Java and J2EE interviews and useful for practicing before appearing on any Java Job interview. This list of Spring interview questions and answers contains questions from Spring fundamentals e.g. Spring IOC and dependency Injection, Spring MVC framework, Spring Security, Spring AOP etc, because of length of this post I haven't included Spring interview questions from Spring JDBC and JMS which is also a popular topic in core Java and J2EE interviews. I suggest to prepare those as well. Any way these Spring questions are not very difficult and based on fundamentals e.g. What is default scope of Spring bean and mostly asked during first round or telephonic round of Java interview. Although you can find answers of these Spring interview questions by doing Google but I have also included some answers for quick reference. As I said Spring  and Spring MVC is fantastic Java framework and if you are not using it than start using it, these questions will give you some head start as well.

Wednesday, September 28, 2011

Top 10 Servlet Interview Question Answers - J2EE

This time its servlet interview questions, I was thinking what to pick for my interview series and than I thought about J2EE and Servlet is my favorite on that space. Servlet is an important part of any J2EE development and serves as Controller on many web MVC frameworks and that’s why it’s quite popular on J2EE interviews. These Servlet questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for any one who is not very familiar with servlet technology.

Servlet interview question and answerAs said earlier this interview question article is part of my earlier series java interview questions , UNIX command interview questions and Java threading interview questions.

You can find answers of all these questions on google but I have also listed my answers fo r quick reference.

Sunday, September 25, 2011

Finally Eclipse supports JDK7 in Eclipse Indigo 3.7.1


Much awaited release of Eclipse with JDK7 is now over, Eclipse has announce release of version Indigo 3.7.1 which will support JDK7.though I already have downloaded Netbeans with JDK7 support I was eagerly waiting for my favorite java development IDE to comes with java7 support. I am expecting this to support all new java7 features including automatic resource management, string in switch and multiple-cache block in exception handling. You can download the new Eclipse 3.7.1 version from here. You can also update your existing eclipse IDE with new feature from Menu-->Help-->Check for
Updates.

eclipse with jdk7, eclipse indigo 3.7.1 with java7There is not much in this release except JDK7 feature, no new feature has been introduced which will probably be released in either 3.8 or 4.2. Java community is still embracing JDK7 but sooner or later it will adopt it and my feeling is that it will happen very soon because it contains the similar features which JDK 1.5 was contained though not that significant but still pretty useful for day 2 day work.


Enjoy




Related Java tutorials

Saturday, September 24, 2011

Code Review Checklist and Best practices in Java

What to review while doing Code review
Code Review and Unit testing is one of best development practice I always recommend, strive for and enforce as much as possible. Even just by doing code review and Junit test case always offer positive result it can be improved a lot by constantly learning with our mistakes , others mistakes and by observing how others are doing it. I always try to get my code review by some one with more experience so that I can capture any domain specific scenario which has been missed during think through process and some with less experience so that he can improve his code readability, have a four eye check and most importantly I found that when i explain my code to some one as part of code review I myself discover many things which can be improved or left out.Overall it always add something and improve code quality and reduce bug.


code review checklist, code review best practicesI also review some one else code and voluntary take part to improve my code understanding ability and offer help to others, In this article I will list things which I look while doing code review. These are the things which I have been accumulated over the years but I also look forward to you guys to contribute your experience, best practices for code review and suggest how you guys do code review. These tips are independent of language and equally apply to Java, .NET or C++ code.

10 points checklist on Code Review


1) Does Code meet functional requirement: first and foremost does code meets all requirements which it should met, point out if anything has been left out.

2) Is there any Side effect of this change: Some time one change in your system may cause bug in other upstream and downstream system and it’s quite possible that new developer or anyone who is writing code might not be available of that dependency. This often directly related to experience in project and I found that the more you know about system and its environment better you able to figure this out.

3) Concurrency: does code is thread-safe? Does it have properly synchronized if using shared resource? Does it free of any kind of deadlock or live-lock? Concurrency bugs are hard to detect and often surfaces in production. Code review is one place where you can detect this by carefully understand design and its implementation.

4) Readability and maintenance:  does code is readable? Or is it too complicate for some-one complete new. Always give value to readability as code is not just for this time it will remain there for long time and you need to read it many times. Another important aspect is maintenance as most of software spends 90% time in maintenance and only 10% time on development it should be maintainable and flexible in first place. You can verify that whether code is configurable or not, look for any hard coding, find out what is going to be changed in near future etc.

5) Consistency: This is part of point 4 but I have made it another separate point because of its importance. This is the best thing you can have in your code which automatically achieves readability. Since many developer and programmer take part in project and they have there own style of coding, it’s in best interest of everybody to form a coding standard and follow it on letter and spirit. For example it’s not good someone using function initialize() and other is using init() for same kind of operation, keep you code consistent and it will look better, read better.

6) Performance: Another important aspect most important if you are writing high volume low latency electronic trading platform for high frequency trading which strives for micro second latency. Carefully monitor which code is going to execute at start-up and which is going to be executed in loop or multiple times, optimize the code which is going to execute more often.

7) Exception handling: Ask does code handles bad input and exception? It should and that too with predefined and standard way which must be available and documented for support purpose. I put this point well above on my chart while doing review because failing on this point can lead your application crash and not able to recover from fault on other system or other part of same application.

8) Simplicity: Always see if there is any simple and elegant alternative available at-least give a thought and try. Many times first solution comes in mind is not best solution so giving another thought is just worth it.

9) Reuse of existing code: See if the functionality can be achieved by using existing code, advantage of doing this is that you are using tried and tested code which reduce your QA time and also give you more confidence. Introducing new libraries introduce new dependency. I prefer not to try anything fancy until it’s absolutely necessary.


10) Unit test: Check whether enough JUnit test cases have been written and cover sufficient percentage of new code. never let you pass the code without Junit test because developer often make excuse of time but believe me its worth to write it.

Not last but least that put a comment on your java file that by whom it has been reviewed, what issue finds are out and status of those. This will make the whole process official and ensures that due diligence would be applied during code review. Its also good to maintain your own code review checklist or a project wise code review checklist and use it every time while doing review. There are so many best practices but I have only included those which I follow and found interesting but as I had said earlier this is the area which always needs improvement and no body is perfect on that. So please contribute your ideas on code review and effective development.

Enjoy

Some older post you may like

How to convert String to Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java can be used to convert String to Date in Java. java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and can convert a particular String which follows that pattern into Date in Java.This is the second part of the article on java.util.Date and String in Java. In the first part we have seen How to convert Date to String in Java. SimpleDateFormat accepts a String in any date format e.g. yyyyMMdd is a date pattern and  20110924 is a String in that format. Now you want to create a java.util.Date object from this String. In this Java tutorial we will see list steps to convert String to Date in Java and then we will see different examples of SimpleDateFormat with different date patterns e.g. ddMMyy or dd-MM-yyyy. Though converting String to Date is quite easy using SimpleDateFormat, but you need to remember that SimpleDateFormat is not thread-safe, which means you can not share same instance of SimpleDateFormat between multiple threads. Avoid storing SimpleDateFormat in static variable and if you want to safely share or reuse SimpleDateFormat, you need to make it thread-safe. One way is to use ThreadLocal variable in Java to make SimpleDateFormat thread-safe, as shown in this example.

How to get google plus invites free

google + (plus) invites free

Hi guys as you know that google plus are a new social networking buzzes a google answer to facebook. But it’s different than facebook in terms of joining the site. It’s not open like facebook instead you need invites to join the google plus many of you might be already in google plus but for those who are not yet join google plus I have something to offer.

I have just joined the google plus thanks to my friend who invited me to join google plus and now I have many google plus invites left with me which I would  like to give you , my readers and anyone who is interested to joining google plus. I have been reading on google plus now and seeing how it is different than facebook. One good thing is that it provides more on privacy front and idea of google circle is quite nice. I am sure it will take a lot of time to topple facebook and its definitely a challenge for google but its a good networking service to join.

google plus invitees free

What you need to do to get google plus invites

Just drop your name and email address as comment and I will send you google invites. if you don't want to publish your email then let me know and I won't publish your comment but will send you the invites in your email.

Enjoy

Friday, September 23, 2011

How to write Production quality code?

We often here the term "production quality code" , some times in interview where interviewee asked to write production quality code for a particular function,Some time discussion between developers and programmers and some time during code review. I know most of you familiar with term but for those who wonder what is production quality code in simple terms its code which can bear the test of time in production environment.

We all develop code in development, than test in QA and finally it gets released in production. But there are lot of difference between test and prod and if you have not coded taking prod environment in mind most likely code will fail in prod or result in exceptions.So what makes production environment different than development environment? Here are few things which I noted:

1) Production is all about load which will expose concurrency issues, load issues, memory and CPU issues.

2) You will get a lot many scenarios in production that you might have thought in development. If think through process is not applied than most likely those scenario has not handled in production.

3) Different data input or incorrect data, one of classic problems in production is the data which gets input to your program, be it from upstream system or any other place you will get all sort of data and if your program doesn't handle those very likely it will suffer.

4) Boundary conditions, this is some what related to above point data and scenarios but most of the boundary condition e.g. null, empty etc exposed in production.


So if a code is written all these things and potentially domain specific things and can sustain test of production than it called a production quality code and believe me it takes a lot of experience, skill and think through process to write production quality code not just in first time even after two or three iteration but as a developer we should always strive for writing production quality code in first attempt.

Now let's see how we can do that, what are the things we should keep in mind:

1) Get your requirements right, understand the problem , talk to user or business person as much as possible this will help you to find different scenario as early as possible. Many times business or user not tell you everything its not there fault but it doesn't come in mind right through. So if you are frequently speaking, discussing and presenting solution to them most likely they will ask questions, give feedback which eventually expose more scenario and subtle details. Here experience plays an important role. More experience or domain knowledge you, much better code you will write.

2) Think through, Think through and Think through. There is no substitute of this, it is more of a skill and art than science but you will get hold of this when you get more experience. For example if user says that you need replay capability in your program. You should be able to think of all possible scenarios where you need to replay and what could be required for that, what would be side effect of that. Does replay would be requested, what if the requesting system went down again, will you be able to re replay etc.

3) Boundary condition, always think that you will get bad input , you will get null or empty, small or very large numbers, function may get called at wrong time etc. you can get rid of this by writing unit test for each boundary condition.

4) Concurrency, this is is the major culprit and big problem which exposes itself in production when due to load multiple thread gets triggered and access your program concurrently. With high speed low latency electronic trading system and with many other java system where its requirement to have a concurrent application this can only be addressed by proper design , if you get the design right you will safe other wise you will need to bear the pain of redesigning or rewriting code. You can also expose concurrency issue by doing load testing in early QA cycles.

5) Exception handling, this is by far most important characteristic of production quality code, it must be able to handle exceptional scenario in clear cut predefined way. Whole program should never be crashed due to one single bad input or scenario.

6) Recoverable, code should be able to recover itself in case of premature closing or crash.

Though these are just some points which I am able to thought, there are lots more and it’s a constant process of improving yourself and I always strive for this. Please share how you guys write production quality code, what are things you guys keep in mind, what questions you guys ask to yourself and to user ?

Thank you.


Related Java Tutorials

Variable argument or Varargs methods from Java 5 with Example - Programming Tutorial

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many argument as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, auto boxing and various others. Variable arguments a relatively small feature but useful for a developer who has been well aware about method and array. Some time we have a scenario that one method can take variable number of argument  and now with varargs from language makes it much easier. In this Java tutorial we will see How variable arguments makes it easy to write convenient method which can accept any number of arguments,  perfect candidates are sum() and average() kind of methods.

This article is in continuation of exploring features of Java programming language. I have already covered fork-join framework from Java 7 and automatic resource management or ARM blocks, if you haven't read them already you may find them useful.

Wednesday, September 21, 2011

10 examples of displaytag in JSP, Struts and Spring

Display tag is one of the best free open source library for showing data in tabular format in a J2EE application using jsp, struts or spring. it is shipped as tag library so you can just include this  in your jsp and add corresponding jar and there dependency in class-path and you are ready to use it. Display tag is my favorite solution for displaying any tabular data because of its inherent capability on paging and sorting. It provides great support for pagination by its own but it also allows you to implement your own pagination solution. On Sorting front you can sort your data based on any column, implement default sorting etc.

display tag examples in jspThere is so much resource available on using display tag including examples, demos and guides. In this article we will see some important points to note while using display tag in jsp. Though this library is very stable and rich in functionality still there are some subtle things which matters and if you don't know you could potentially waste hours to fix those things. These are the points I found out while I was using displaytag in my project and I have listed those down here for benefits of all.

displaytag examples
I have outlined all the examples based upon task I had to perform and due to those tasks I discovered and get myself familiar with displaytag. It’s my personal opinion that task based approach works better in terms of understanding something than feature based. It’s simply easy for mind to understand problem first and then solution.

1) Provide UID while using two tables in one page.
In many scenarios we need to show two separate tables in one jsp page. We can do this by using two tag easily but the catch is that sorting will not work as expected. When you sort one table, second table will automatically sort or vice-versa. To make two tables independent of each other for functionality like exporting and sorting you need to provide "uid" attribute to table tag as shown below. I accidentally found this when I encounter sorting issue on display tag.

<displaytag:table name="listofStocks" id="current_row" export="true" uid="1">
<displaytag:table name="listofStockExchanges" id="current_row" export="true" uid="2">

just make sure "uid" should be different for each table.
 


2) Displaytag paging request starts with "d-"
There was bug in one of our jsp which shows data using displatag, with each paging request it was reloading data which was making it slow. Then we thought to filter out displaytag paging request and upon looking the pattern of displaytag paging request we found that it always starts with "d-", so by using this information you can filter out display tags paging request. Since we were using spring it was even easier as shown in below

Example:

Map stockParamMap = WebUtils.getParametersStartingWith(request, "d-");
if(stockParamMap.size() !=0){
out.println("This request is displaytag pagination request");
}

3) Getting reference of current row in displaytag
Many times we require reference of current row while rendering display tag data into jsp page. In our case we need to get something from currentRow and then get Something from another Map whose key was value retrieved from current row, to implement this of course we some how need reference of current row in display tag. After looking online and displaytag.org we found that by using "id" attribute we can make current row reference available in pageScope. Name of variable would be the value of "id" attribute, this would be much clear by seeing below example:


<displaytag:table name="pennyStocks" id="current_penny_stock" export="true" uid="1">
<di:column title="Stock Price" value="${pennyStockPrice[current_penny_stock.RIC]}" sortable="true" />

This way we are displaying stock price from pennyStockPrice Map whose key was RIC(Reuters Information Code) of penny Stock. You see name of variable used to refer current row is "current_penny_stock"

4) Formatting date in displaytag in JSP
Formatting date and numbers are extremely easy in display tag, you just need to specify a "format" attribute with <displaytag:column> tag and value of this tag would be date format as we used in SimpleDateFormat in Java. In Below example I am showing date in "yyyy-MM-dd" format.


<di:column title="Stock Settlement Date" property="settlementDate" sortable="true" format="{0,date,yyyy-MM-dd}" />

You can also implement your own table decorator or column decorator but I found this option easy and ready to use.


5) Sorting Columns in display tag
Again very easy you just need to specify sortable="true" with <displaytag:column> tag and display tag will make that column sortable. Here is an example of sortable column in display tag.

<di:column title="Stock Price" property="stockPrice" sortable="true" />


6) Making a column link and passing its value as request parameter.
Some time we need to make a particular columns value as link may be to show another set of data related to that value. we can do this easily in display tags by using "href" attribute of <displaytag:column> tag, value of this attribute should be path to target url.If you want to pass value as request parameter you can do that by using another attribute called "paramId", which would become name of request parameter.

Here is example of making link and passing value as request parameter in displaytags.

<di:column property="stockSymbol"  sortable="true" href="details.jsp" paramId="symbol"/>

Values on this column will appear as link and when user click on the link it will append a request parameter "symbol" e.g symbol=Sony


7) Default sorting and ordering in displaytag
If you want that your table data is by default sorted based upon a particular column when displayed than you need to defaine a column name for default sorting and an order e.g. ascending or descending. You can achieve this by using attribute "defaultsort" and "defaultorder" of <displaytag:table> tag as shown in below example.

<displaytag:table name="pennyStocks" id="current_penny_stock" export="true" defaultsort="1" defaultorder="descending" uid="1">


This will display table which would be sorted on first column in descending order.

8) Sorting whole list data as compared to only page data in display tag
This was the issue we found once we done with our displaytag jsp. we found that whenever we sort the table by clicking on any sortable column header it only sort the data visible in that page, it was not sorting the whole list provided to display tag I mean data which was on other pages was left out. That was not the desirable action for us. Upon looking around we found that display tag by default sort only current page data but you can override this behavior by providing a displaytag.properties file in classpath and including below line in

displaytag.properties:
sort.amount = list

9) Configuring displaytag by using displaytag.properties
This was important piece of information which we are not aware until we hit by above mentioned issue. Later we found that we can use displaytag.properties to customize different behaviours, appearence of displaytag. Another good behavior we discoved was showing empty table if provided list is null or empty. You can achieve this by adding line "basic.empty.showtable = true". Here was how our properties file look like


//displaytag.properties
sort.amount = list
basic.empty.showtable = true
basic.msg.empty_list=No results matched your criteria.
paging.banner.placement=top

10) Specifying pagesize for paging in a JSP
You can specify how many rows you want to shwo in one page by using "pagesize" attribute of <displaytag:table>. We prefer to use it from configuraiton because this was subject to change.

Overall we found that displaytag was quite rich in functionality, easy to use and highly configurable. Displaytag is also very extensible in terms of customizing export or pagination functionality. Displaytag.org has some very good examples and live demo addressing each of display tag functionality and those are excellent starting point as well. No matter whether you are using struts, spring or plain sevlet based framework for tabular data displaytag is a good choice.

Note: In <displaytag:table> displaytag is tag prefix I used in while declaring tag library using <@taglib> in JSP.

Related Java Tutorials

Tuesday, September 20, 2011

Difference between HashMap and HashSet in Java

HashMap vs HashSet is the most frequently asked question during any core java interview and interview is not said completed until they will not cover the Collection Framework and multi-threading interview and collections are uncompleted without Covering Hash Set and Hash Map.
Both HashMap and HashSet are part of collection framework which allows us to work with collection of objects. Collection Framework has their own interfaces and implementation classes. Basically collection is divided as Set Interface, List and Queue Interfaces. All this interfaces have their own property also apart from they get from collection like Set allows Collection of objects but forbids duplicate value, List allows duplicate along with indexing.Queue woks on FCFS algorithm.

First we have one look on What HashMap and Hashset is then will go for Differences between HashSet and HashMap

What is HashSet in Java?

HashMap vs HashSet, difference between HashMap and Hashset in JavaHashSet  is implementation of Set Interface which does not allow duplicate value all the methods which are in Collection Framework are also in Set Interface by default but when we are talking about Hash set the main thing is objects which are going to be stored in HashSet must override equals() and hashCode() method so that we can check for equality and no duplicate value are stored in our set.if we have created our own objects we need to implement hashCode() and equal() in such a manner that will be able to compare objects correctly when storing in a set so that duplicate objects are not stored,if we have not override this method objects will take default implementation of this method.


public boolean add(Object o)  Method is used to add element in a set which returns false if it’s a duplicate value in case of  HashSet otherwise returns true if added successfully.


What is HashMap?

HashMap is a implementation of Map Interface, which maps a key to value.Duplicate keys are not allowed in a map.Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.HashMap allows null values and null keys.HashMap is not synchronized,but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our hashmap and one thread is structurally change our map.

public Object put(Object Key,Object value) method is used to add element in map.

You can read more about HashMap in my article How HashMap works in Java and Difference between HashMap and hashtable in Java

Difference between HashSet and HashMap in Java

Following are some differences between HashMap and Hashset:


Hash Map
Hash Set
HashMap  is a implementation of Map interface
HashSet is an implementation of Set Interface
HashMap Stores data in form of  key value pair
HashSet Store only objects
Put method is used to add element in map
Add method is used to add element is Set
In hash map hashcode value is calculated using key object
Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.
HashMap is faster than hashset because unique key is used to access object
HashSet is slower than Hashmap


Please let me know if you need any other difference between HashSet and HashMap in Java and I will add them here.


Related Java Tutorials



Saturday, September 17, 2011

Java 1.5 Generics Tutorial: How Generics in Java works with Example of Collections, Best practices, Gotchas

Java Generics Tutorial
Generics in Java is one of important feature added in Java 5 along with Enum, autoboxing and varargs , to provide compile time type-safety. Generics is also considered to be one of tough concept to understand in Java and somewhat it’s true as well. I have read many articles on generics in Java, some of them are quite good and detailed but I still felt that those are either too much technical or exhaustively detailed, so I thought to write a simple yet informative article on Java generics to give a head start to beginners without bothering there head too much. In this Java generics tutorial I will cover How Generics works in Java, Mysterious wild-cards in Generics and some important points about Generic in Java. I will try explaining generics concept in simple words and simple examples. On a different note, If you like to learn new concepts by following books then you should check Java Generics and Collection, one of the best book on Generics, which covers from basics to best practices.

By the way I thought about writing on Java Generics when I completed my post on Advanced Example of Enum in Java. Since Enum and Generics are introduced at same time in JDK 5. If you like to read about generics than you can also check my other tutorials on generics e.g. 10 generics interview question in Java and Difference between bounded and unbounded wildcards in Generics.

Friday, September 16, 2011

How to Convert Date to String in Java with Example

Some times we need to convert java.util.Date to string in java  may for displaying purpose I need it that while working on displaytag then I thought about this article  to list down various way of converting this in various ways, after some reading I found that SimpleDateFormat makes this quite easy. To get the feel of Date API in java and to familiarize ourselves with these classes we will see different examples of converting date to String in our application. Both DateFormat and SimpleDateFormat class belongs java.text package and they are very powerful and you can use them for conversion. it also good for parsing string into date and can be used to show in various locale also.

Difference between SendRedirect() and Forward() in JSP Servlet

Difference between SendRedirect and forward is one of classical interview questions asked during java web developer interview. This is not just applicable for servlet but also for JSP in which we can use forward action or call sendRedirect() method from scriptlet. Before examining difference on forward and SendRedirect let’s see what send Redirect method and forward method does.

SendRedirect ():  

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

Thursday, September 15, 2011

How to use Fork Join in Java 1.7 - Tutorial with Example

What is fork Join framework in Java: Already popular project coin of JDK7 release has presented lot of good feature e.g automatic resource management, string in switch case, better exception handling in JDK7 etc. On of other important feature to note is fork join as name implies it divide one task into several small task as a new fork means child and join all the fork when all the sub-tasks complete. Fork/join tasks is “pure” in-memory algorithms in which no I/O operations come into picture.it is based on a work-stealing algorithm. Concept of fork join would be much clear by following diagram.

Wednesday, September 14, 2011

InvokeLater and InvokeAndWait in Java Swing (an example tutorial)

Everyone who is doing programming in java swing has to come across invokeAndWait and invokeLater provided by SwingUtilites. In this java swing tutorial we will learn about both invokeLater() and invokeAndwait() method. In first part we will mostly focus on invokeLater and will find answers of questions like What is invokeLater, how to use invokelater in java swing, example of invokelater in swing etc while in second part of this invokeLater tutorial we will learn more about invokeAndWait method in java swing and will learn Why we need InvokeAndWait, how to use InvokeAndWait method in java Swing and differences between invokelater and invokeAndWait.

Finally we will see code example of both invokeLater and invokeAndWait in Swing and will be able to decide when to use invokeLater and when to use invokeAndWait while doing Swing programming. 
We will also see famous Swing interview questions "difference between invokeLater and invokeAndWait" at end of article.

Sunday, September 11, 2011

How to find IP Address from hostname in Windows Linux and Unix

IP Address from hostname in Windows and Linux
How many times in a day you have a hostname and you want to know the IP address? Host name to IP address and IP address to hostname conversion is one of frequent thing which we need to do for many things when dealing with networking command in unix. For one command we need IP address for other we need hostname even from bash script some time we require hostname and some time we look for IP address. networking commands are not as popular as find command or grep command but they are equally important and if you working in Windows or UNIX environment you must learn them and they should also be included in any list of Unix commands for beginners. By the way In this hostname to IP address tutorial I will show you how to get IP address from hostname or computer-name in Unix or Linux and how to get hostname if you have IP address. If you are looking a way to do it via Java program then you can also see my post how to find IP address of localhost in Java.

Saturday, September 10, 2011

Top 10 Java Swing interview questions answers asked in Investment banks

Java Swing is heavily used in developing trading application front end. Doesn’t matter whether its front office or middle office you will find swing GUI everywhere. Swing GUI is used to developed Order entry system, order monitoring GUI and for other tools which trader or operations can use on different trade life cycle. Due to it’s heavily usage there are lot of requirements of java swing developer in IB. In this post we will see some java swing interview questions asked in various interview. These swing interview questions are based on my experience as well as collected from friends and colleagues. So if you are going for any java swing development job interview you can use these java swing interview questions for practice, answers of swing question are also given.

swing interview questions answers in javaThis article is in continuation of my previous interview articles like 10 interview questions on Singleton pattern in Java, 10 interview questions answers on Serialization in Java and 15 java threading interview question answers and.If you haven’t read them already you may find them useful for your job interview or practicing purpose

Swing Interview questions answers

Let’s start with simple questions and then moving on to complex and little harder one, normally that’s how it goes in swing interview as well.

1) What is Event-Driven-Thread (EDT) in Swing?
Event-Driven-Thread or EDT is a special thread in Swing and AWT. Event-Driven Thread is used to draw graphics and listen for events in Swing. You will get a bonus point if you able to highlight that time consuming operations like connecting to database, opening a file or connecting to network should not be done on EDT thread because it could lead to freezing GUI because of blocking and time consuming nature of these operations instead they should be done on separate thread and EDT can just be used to spawn those thread on a button click or mouse click.

2) Does Swing is thread safe? What do you mean by swing is not thread-safe?
This swing interview questions is getting very popular now days. Though it’s pretty basic many developer doesn't understand thread-safety issue in Swing. Since Swing components are not thread-safe it means you can not update these components in any thread other than Event-Driven-Thread. If you do so you will get unexpected behavior. Some time interviewer will also ask what are thread-safe methods in swing which can be safely called from any thread only few like repaint() and revalidate().

3) What are differences between Swing and AWT?
One of the classic java swing interview questions and mostly asked on phone interviews. There is couple of differences between swing and AWT:

1) AWT component are considered to be heavyweight while Swing component are lightweights
2) Swing has plug-gable look and feel.
3) AWT is platform depended same GUI will look different on different platform while Swing is developed in Java and is platform dependent.

4) Why Swing components are called lightweight component?
Another popular java swing interview question, I guess the oldest that is generally comes as followup of earlier question based on your answer provided. AWT components are associated with  native screen resource and called heavyweight component while Swing components is uses the screen resource of an ancestor instead of having there own and that's why called lightweight or lighter component.

5) What is difference between invokeAndWait and invokeLater?
This swing interview question is asked differently at different point. some time interviewer ask how do you update swing component from a thread other than EDT, for such kind of scenario we use SwingUtilities.invokeAndWait(Runnable r) and SwingUtilities.invokeLetter(Runnable r) though there are quite a few differences between these two, major one is invokeAndWait is a blocking call and wait until GUI updates while invokeLater is a non blocking asynchronous call. In my opinion these question has its own value and every swing developer should be familiar with these questions or concept not just for interview point of view but on application perspective. you can read more on my post  How InvokeAndWait and InvokeLater works in Swing

6) Write code for JTable with custom cell editor and custom cell renderer?
Now comes harder part of swing interviews, questions asked in this part of Swing interview is mostly about writing code and checking developer’s capability of API familiarity, key concept of swing code etc.

JTable is one of favorite topic of all Swing interviews and most popular questions on swing interviews are from JTable why? Because here interviewer will directly asked you to write code another reason is JTable heavily used in all Electronic trading GUI. GUI used for online stock trading uses JTable to show data in tabular format so an in depth knowledge of JTable is required to work on online trading GUI developed in Swing. While this question is just an example questions around JTable are mostly centered around updating table, how do you handle large volume of data in table, using customize cell renderer and editor, sorting table data based on any column etc. so just make sure you have done quite a few handsone exercise on JTable before appearing for any java swing interview in IB.

7) Write code to print following layout (mainly focused on GridBag layout)?
After JTable second favorite topic of swing interviewer is GridBagLayout. GridBagLayout in swing is most powerful but at same time most complex layout and a clear cut experience and expertise around GridBagLayout is desired for developing Swing GUI for trading systems. No matter whether you are developing GUI for equities trading, futures or options trading or forex trading you always required GridBagLayout. Swing interview question on GridBagLayout will be mostly on writing code for a particular layout just like an example shown here. In which six buttons A, B, C, D, E and F are organized in certain fashion.


8) How do you handle opening of database, file or network connection on a click of button?
This one is one of the easy java swing interview question. Interviewer is interested on whether you know the basic principle of Java GUI development or not. answer is you should not do this operation in EDT thread instead  spawn a new thread from actionListener or button and disable the button until operation gets completed to avoid resubmitting request. Only condition is that your GUI should always be responsive no matter what happens on network connection or database connection because these operations usually take time.

9) Prediction of output of code?
This is another category of Swing interview questions asked in IB whether they will give you code and asked what would be the output , how will the GUI look like. This type of question is based upon how well you understand and visualize the code. Whether you are familiar with default layout manager of various component classes or not e.g. default layout of JFrame is BorderLayout. So do some practice of these kinds of java Swing interview questions as well?

10) Question around JList like Creating a Jlist component such which should contain all the asset classes like stocks, futures, options and derivatives etc in form of String. But constraint is JList should always be sorted in Ascending order except that all assets which begins with "Electronic trading” appears on top?
This is an excellent java swing interview questions which is based on real world task and focus on JList component, Sorting and customizing JList model. For sorting you can use comparable in Java and by customizing the JList model you can display content as requested. Once you successfully answer this question there may be some followup on customizing the color of cell etc which can be done by customizing renderer.

These are just few swing interview questions which I find interesting. Swing is particular important in Front office area and there is lot of demand of good Swing developers in Wall Street firms. If you have good skills on FIX Protocol + Core Java + Swing you would be most sought after in electronic trading domain. Anyway this list is no means complete so please share any interesting java swing interview questions you have faced.


My Previous interview articles

Friday, September 9, 2011

How to work with transient variable in java (an example tutorial)

Transient keyword in java is comparatively less common than any other keyword like volatile.since transient is less common it becomes even more important to understand correct usage of it. In One word transient keyword is used in serialization process to prevent any variable from being serialized, so if you have any field which is not making sense to serialize, you can simply declare that as transient and it won't be serialized.In this article we will revise some basics like
What is transient variable in java, why do we need transient variable and most importantly where should we use transient variable or which fields need to be declared as transient with example.

What is transient variable in Java?

transient variable, transient keyword javaIn simple sentence any variable which is modified with transient keyword becomes transient variable in java.But before understanding about transient variable let recap something about serialization in java. Serialization is a process by which object's state is saved by JVM and during deserializaiton it’s recovered by JVM. During Serialization all property of object gets saved except static and transient. So if we would like to exclude any property of an object from being serialized we mark it transient and then JVM doesn't serialize it. While marking any property transient its worth noting to provide it a default value during deserialization otherwise deserialized object is not properly usable.

Why do we need transient variable in java?

Transient keyword provides you some control over serialization process and gives you flexibility to exclude some of object properties from serialization process. Some time it does make sense not to serialize certain attributes of an object, we will see which variables should not be serialized and should be made transient in next section.

Which variable you should mark transient?

This is a good question; since we know the purpose of transient keyword or having transient variable its make sense to think about which variable should be marked as transient. My rule is that any variable whose value can be calculated from other variables doesn't require to be saved. For example if you have a field called "interest" whose value can be derived from other fields e.g. principle, rate, time etc then there is no need to serialize it.

Another example is of word count, if you are saving article then no need to save word count, because it can be created when article gets deserialized. Another good example of transient keyword is "Logger" since most of the time you have logger instance for logging in Java but you certainly don't want it to serialize correct?

Example of transient variable in java

To understand the concept of transient variables let see a live example in java.


public class Stock {
    private transient Logger logger = Logger.getLogger(Stock.class); //will not serialized
    private String symbol; //will be serialized
    private BigInteger price; //serialized
    private long quantity; //serialized
}

Important points about transient keyword in java

Here are few important points about transient variables in java which I found, let me know if you have some more which I missed out here and I will include here.

1) Transient keyword can only be applied to fields or member variable. Applying it to method or local variable is compilation error.

2) Another important point is that you can declare an variable static and transient at same time and java compiler doesn't complain but doing that doesn't make any sense because transient is to instruct "do not save this field" and static variables are not saved anyway during serialization.

3) In similar way you can apply transient and final keyword together to a variable compiler will not complain but you will face another problem of reinitializing a final variable during deserialization.

4) Transient variable in java is not persisted or saved when an object gets serialized.


That's all from me on transient keyword, let me know how do you use it and if you know any pecularity about transient keyword or something which we need to be aware while using it and missed out here. You can also refer’s Sun Glossary for meaning of different keywords in Java.


Related tutorials in Java