Monday, December 30, 2013

Inter Thread Communication in Java using Wait Notify Example

Wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object. Classical example of wait and notify method is Producer Consumer design pattern, where One thread produce and put something on shared bucket, and then tell other thread that there is an item for your interest in shared object, consumer thread than pick than item and do his job, without wait() and notify(), consumer thread needs to be busy checking, even if there is no change in state of shared object.

Wednesday, December 25, 2013

How to redirect a page or URL using JavaScript and JQuery

Redirecting a web page means, taking user to new location. Many website use redirect for many different reasons, e.g. Some website redirect user from old domain to new domain, some redirect from one page to another e.g. a more relevant page. If you are Java programmer, and worked previously with Servlet and JSP, then you might be familiar with SendRedirect and Forward methods, which are used to redirect user in web applications. Actually there are two kinds of redirect, Server side redirect and client side redirect. In Server side redirect, server initiate redirection, while in client side redirect, client code does the redirection. Redirecting a web page using JavaScript and JQuery is a client side redirection.

Thursday, December 19, 2013

JUnit Testing Tips - Constructor is Called Before Executing Test Methods

Most of Java programmers either use JUnit or TestNG for there unit testing need, along with some mock object generation libraries e.g. Mockito, but not everyone spend time and effort to learn subtle details of these testing libraries, at least not in proportion of any popular framework e.g. Spring or Hibernate. In this blog post, I am sharing one of such details, which has puzzled me couple of years ago. At that time, though I had been using JUnit for significant time, I wasn't aware that code written inside constructor of Test class is executed before each test method.  This behaviour of JUnit has caused, some of my test to failed and putting hours of investigation in my code, without realizing that this is happening because of JUnit is initializing object by calling constructor before executing test method annotated with @Test annotation.

Thursday, December 12, 2013

How to configure Log4j in Java program without XML or Properties File

Sometime configuring Log4j using XML or properties file looks annoying, especially if your program not able to find them because of some classpath issues, wouldn't it be nice if you can configure and use Log4j without using any configuration file e.g. XML or properties. Well, Log4j people has thought about it and they provide a BasicConfigurator class to configure log4j programmatically, thought this is not as rich as there XML and properties file version is, but it's really handy for quickly incorporating Log4j in your Java program. One of the reason programmer prefer to use System.out.println() over Log4j, of-course for testing purpose, because it doesn't require any configuration, you can just use it, without bothering about XML or properties file configuration, but most programmer will agree that, they would prefer to use Log4j over println statements, even for test programs if it's easy to set them up.

Wednesday, December 4, 2013

When to make a method final in Java

Final keyword in Java is not as mysterious as volatile or transient, but still, it creates a lot of doubts on programmers mind. I often receive questions like, When to make a method final in Java or When to make a method static in Java, later I answered in my earlier post. Questions like this are not trivial, knowing what a keyword does is just small part of mastering that functionality. Similar to the real world, where knowing that a sword can cut a lot of things is not enough for a warrior to survive, you need to know how to use that and more importantly, use it effectively. Final keyword can be applied to a class, methods and variable and has a different meaning for each of them, but the motive remains same, it state completeness, it opposes change. For example, final class can not be extended, value of final variable cannot be changed and a final method can not be overridden in Java.

Friday, November 29, 2013

Java vs Python - Which Programming Language Should Learn First

Java and Python are two of most popular and powerful programming language of the present time. Beginner programmer often get confused, one of the most frequently asked question is should I learn Java or Python, Is Python is good programming language to start with, Which programming language would you recommend for beginners to learn first etc. Since I am a Java developer, my opinion is biased, I will always suggest you start with Java and then learn Python, but if you ask this question to a Python developer, you might get just opposite answer. I have well documented  my reasons as Why Java is best Programming language and Why a programmer should learn Java. One of the most important reasons you would see on that blog post is strong Java community, which will help you though out your Java career.

Thursday, November 28, 2013

Difference between static vs non static method in Java

In this article, we will take a look at the difference between static and non-static method in Java, one of the frequently asked doubt from Java beginner. In fact, understanding static keyword itself is one of the main programming fundamental, thankfully it's well defined in Java programming language . A static method in Java belongs to class, which means you can call that method by using class name e.g. Arrays.equals(), you don't need to create any object to access this method, which is what you need to do to access non-static method of a class. Static method is treated differently by compiler and JVM than non-static methods, static methods are bonded during compile time, as opposed to binding of the non static method, which happens at runtime.

Monday, November 25, 2013

Java 8 Tutorials, Resources, Books and Examples to learn Lambdas, Stream API and Functional Interfaces

While the release of Java 8 is still a few month away, GA is scheduled is in early next year (March 2014), Java community is already buzzing with the expectation of functional programming and lambda expression. Many developers, programmers, and bloggers have already shared lots of  really good tutorial to learn lambda expressions, probably the next big thing in Java world. While the term "lambda expression" may sound abstract and academic, Java 8 Lambdas can have a big impact on how you program every day. Java 8 is coming up with  Lambda expressions, Stream API, Functional interfaces, new Date and Time API and default methods, which has been eagerly awaited by the world. As a professional Java developer, you will have to learn Java 8 one day, and it's better to do sooner than later.

Friday, November 22, 2013

Difference between char, varchar, nchar and nvarchar data type in SQL Server database

What is the difference between char and varchar in SQL, followed by nchar and nvarchar, is one of the popular SQL interview questions, and surprisingly not every programmer knows this basic difference. If you go with the name, which you should, then you can figure out that char is a fixed length data type while varchar should be variable length data type. Though all char, varchar, nchar, and nvarchar are used to store text or String data there are subtle differences between them. As I said char is fixed length, which means a variable or a column e.g. Zipcode char(10) will take only 10 bytes to store data, including space.

Wednesday, November 20, 2013

Scala vs Java - Differences and Similarities

Scala is new generation JVM language, which is generating popularity as an alternative of arguably one of the most popular language Java. It's not yet as popular as Java, but slowly getting momentum. As more and more Java developers are learning Scala and inspired by Twitter, more and more companies are using Scala, it's future looks very bright. To start with, Scala has several good feature, which differentiate it from Java, but same time it has lot of similarities as well e.g. both Scala and Java are JVM based language, You can code Scala in Java way and Scala can use any Java library, which in my opinion a great decision made by designers of Scala.

Monday, November 18, 2013

Do you need to pass OCAJP before taking OCPJP - Java Certification for SE 7

One thing, which I certainly noticed after Oracle's acquisition of Sun Microsystems is creating confusion around Java certifications like hell. I used to remember those days, where Java Certifications are well defined and well known e.g. SCJP, SCWCD, SCBCD etc, but currently, Java certification for SE 7 is known as either SCJP 7, OCJP 7 or even OCPJP 7. By the way, the official name of two most sought after Java certifications is Oracle Certified Associate, Java SE 7 Programmer ( Code: 1Z0-803) and Oracle Certified Professional, Java SE 7 Programmer ( Code 1Z0-804 ).  I receive lots of questions regarding Java Certifications for Java SE 6 and 7, with a range of queries from how to prepare for the exam, to suggestions on books, resources, and mock exams.

Thursday, November 14, 2013

Java Array Tutorial and Example for Beginners

Array is one of the most important data structure in any programming language, at same time different programming languages implement and treat array differently. Any one who is done some programming knows value of array and importance of knowing about array type, using them in there program. Together with linked list, array forms a set of basic data-structures. Though Java offers excellent Collection API and some of collection classes like ArrayList and  HashMap , they are internally based on array.  If you are coming from C or C++ background then you will find some difference about how array behaves there and how it does in Java, most notable difference between array in C and array in Java is bounds checking. C compiler doesn't check if program is accessing valid array index, while in Java, JVM does that and throws ArrayIndexOutOfBoundException, if program tries to access invalid array index. In this Java article, we will take a look on array in Java, both primitive and object arrays. It's a collection of important things about Java array and there properties.

Monday, October 28, 2013

How to use multiple JQuery UI Date Picker or Datepicker in HTML or JSP page

We often needs to use multiple JQuery date picker in one HTML or JSP page, classical example is online flight booking for return trips, where you need to pick departure date and arrival date from two separate datepickers. While designing HTML forms either statically or dynamically using JSP, you may want to associate date picker with multiple input text field, paragraph or any other HTML elements. By using JQuery UI and some help from CSS ID and class selector, we can easily use multiple datepicker in one HTML page. All you need to do is, declare a CSS class say .datepicker and apply that class to all HTML elements which needs date picker, for example we have associated date picker with 4 input text fields, which has .datepicker class. By using a class, it becomes extremely easy to select all those element using JQuery class selector, and once you got all those element, you can just call datepicker() methods. This method does all the hard-work and associate a date picker object with selected items, that's it. Now you are ready to use multiple date picker in your HTML or JSP page, let's see the complete code. By the way if you are just starting with jQuery than I highly recommend Head First Query, it’s easy to read  and contain some non trivial example to learn jQuery quickly.

Friday, October 4, 2013

Database Website to Run and Practice SQL Query Online for FREE - SQLFiddle

Other day, I was looking for a website to execute SQL query online, since I have uninstalled Microsoft SQL Server because of memory and CPU constraint and I don't want to install it again, just for executing another query. Also, installing database is pain, it takes time and eats up lots of resources e.g. RAM memory, CPU etc; Given so many database to work with e.g. Oracle, MySQL, Sybase, PostgreSQL and SQLLite, it's not really possible to have all of them in your poor laptop. Fortunately my search leads be to this wonderful site called SQLFiddle, this is what exactly I wanted. This site offers support for lot of popular databases, allows you to build your database schema online and execute SQL query on the fly. I couldn't have asked more, It's a great resource to learn and practice SQL queries online. Apart from many sweet feature, it also allows you to share your problem with community. If you are writing a complex query and stuck in middle, looking for help, you can create your schema on SQLFiddle and can share with your query to any forum or question answer website like StackOverFlow or any forum. 

Wednesday, October 2, 2013

What is PriorityQueue or priority queue data structure in Java with Example - Tutorial

PriorityQueue is an unbounded Queue implementation in Java, which is based on priority heap. PriorityQueue allows you to keep elements in a particular order, according to there natural order or custom order defined by Comparator interface in Java. Head of priority queue data structure will always contain least element with respect to specified ordering. For example, in this post, we will create a PriorityQueue of Items, which are ordered based upon there price, this will allow us to process Items, starting from lowest price. Priority queue is also very useful in implementing Dijkstra algorithm in Java. You can use to PriorityQueue to keep unsettled nodes for processing. One of the key thing to remember about PriorityQueue in Java is that it's Iterator doesn't guarantee any order, if you want to traverse in ordered fashion, better use Arrays.sort(pq.toArray()) method. PriorityQueue is also not synchronized, which means can not be shared safely between multiple threads, instead it's concurrent counterpart PriorityBlockingQueue is thread-safe and should be used in multithreaded environment. Priority queue provides O(log(n)) time performance for common enqueing and dequeing methods e.g. offer(), poll() and add(), but constant time for retrieval methods e.g. peek() and element().

Monday, September 30, 2013

How clone method works in Java?

The clone() is a tricky method from java.lang.Object class, which is used to create a copy of an Object in Java. The intention of the clone() method is simple, to provide a cloning mechanism, but somehow it's implementation became tricky and has been widely criticized from a long time. Anyway, we will not go to classic debate of clone in Java, at least for now; instead, we will try to learn how clone method works in Java. To be fair, understating cloning mechanism in Java is not easy and even experienced Java programmer fail to explain how cloning of mutable object works, or a difference between deep and shallow copy in Java.

Tuesday, September 24, 2013

JSTL forTokens Tag Example - Split String in JSP

JSTL forTokens tag is another tag in core JSTL library to support Iteration or looping. It effectively complements, more useful <c:forEach> tag, by allowing you to iterate over comma separated or any delimited String. You can use this tag to split string in JSP and can operate on them individually. forTokens tag has similar attribute like forEach JSTL tag except one more attribute called delims, which specifies delimiter. For example to iterate over colon separated String "abc:cde:fgh:ijk", delims=":". By the way, forTokens tag also accept multiple delimiter, which means, you can split a big string into token based upon multiple delimiter e.g. colon(:) and pipe (|), This will be more clear, when we will see examples of JSTL forTokens tag in JSP. Rest of attribute e.g. items, var, varStatus, begin, end and step are same, as they are in case of <c:forEach> tag. For quick review, items specify String which needs to be split-ed in token and var hold current String.

Tuesday, September 3, 2013

How Maven find dependency JARs while building Java Project

One of the most attractive feature of Apache Maven framework it to manage dependency JARs, but do you know, How Maven finds dependency JAR while building Java project? From where does it download all JAR files? How does Maven search for a particular dependency? In fact, these are some of the frequently asked questions by Maven beginners. Many Java programmer started using Maven as build tool, because of it's dependency management advantages. Since almost all Java project uses lot's of open source libraries, which means adding multiple JAR into classpath. In fact, this dependency on JAR file is one of the most time consuming part of setting up a Java project in Eclipse. Maven comes in picture, and allows you to just declare dependency in pom.xml file, rest will be taken care by Maven. In this article, we will take a closer look on How Maven manages dependencies and How does it finds respective JAR files during build  process.

Wednesday, August 28, 2013

10 Equals and HashCode Interview Questions in Java

Equals and HashCode methods in Java are two fundamental methods from java.lang.Object class, which is used to compare equality of objects, primarily inside hash based collections such as Hashtable and HashMap. Both equals() and hashCode() are defined in java.lang.Object class and there default implementation is based upon Object information e.g. default equals() method return true if two objects are exactly same i.e. they are pointing to the same memory address while default implementation of hashcode method return int and implemented as a native method. The similar default implementation of toString() method, returns type of class, followed by memory address in hex String.

Thursday, August 22, 2013

3 CDN URL to load jQuery into Web Page from Google, Microsoft

jQuery is one of the most popular and powerful JavaScript libraries, but in order to use it, you need to load into your web page using standard HTML <script> tag. Based on whether your web page is public accessible or for an organization, you can either choose to load the jQuery library from local file system, bundled inside your web application or you can directly download using one of the content delivery network (CDN) e.g. Google or Microsoft CDN. Choosing CDN to download jQuery can offer a performance benefit because there servers are spread across the globe. This also offer an advantage that if visitor of your site has already downloaded a copy of jQuery from the same CDN, then it won't have to be re-downloaded.  By the way if you want to bundle jQuery into your web application or want to load it from local file system, you can always download latest version of jQuery from jQuery site at http://jquery.com. Installing jQuery required this library to be placed inside your web application and using the HTML <script> tag to include it into your pages e.g. <script type="text/JavaScript" src="scripts/jquery-1.10.2.js"></script>

Tuesday, August 20, 2013

Why use SLF4J over Log4J for logging in Java

Every Java programmers know that logging is critical for any Java application, especially server-side application, and many of them are already familiar with various logging libraries e.g. java.util.logging, Apache log4j, logback, but if you don't know about SLF4J, Simple logging facade for Java,  then it's time to learn and use SLF4J in your project. In this Java article, we will learn why using SLF4J is better than using log4j or java.util.logging. It’s been a long time, since I wrote 10 logging tips for Java programmer,I don’t remember anything I have writing about logging. Anyway, let’s get back to the topic, on contrary to all those logging libraries, there is a major difference between them and SLF4J. SLF4J or Simple logging Facade for Java is not really a logging implementation, instead, it's an abstraction layer, which allows you to use any logging library in the back-end. If you are writing API or utility library, which can be used internally or externally, then you really don't want that any client, which uses your library, should also stick with your choice of logging library. 

Friday, August 16, 2013

How to Sort List in reverse Order in Java Collection Framework with Example

Java Collection Framework provides a convenient reverse comparator, to sort List of objects in reverse order.  You can obtain reverse Comparator, by calling Collections.reverseOrder(), which by default sort List of Integer in reverse numeric order and List of String in reverse alphabetic order. It actually reverse natural ordering of objects imposed by Comparable interface. Apart from this method, Collections class also provides an overloaded method Collections.reverseOrder(Comparator cmp), which takes a Comparator, and sort List on reverse order of that Comparator. So next time if you need to sort your Collection in reverse order, you don’t need to write any extra comparator by yourself, you can directly leverage reverse comparator provided by java.util.Collections class. It is as simple as calling Collections.sort() method providing comparator wrapped into Collections.reverseOrder() method. By using these two methods, you can sort any List implementation e.g. ArrayList, LinkedList or Vector in Java.

Wednesday, August 14, 2013

How to fix java.net.SocketException: Too many files open java.io.IOException in Tomcat, Weblogic Server

Not many Java programmers knows that socket connections are treated like files and they use file descriptor, which is a limited resource. Different operating system has different limits on number of file handles they can manage. One of the common reason of java.net.SocketException: Too many files open in Tomcat, Weblogic or any Java application server is, too many clients connecting and disconnecting frequently at very short span of time. Since Socket connection internally use TCP protocol, which says that a socket can remain in TIME_WAIT state for some time, even after they are closed. One of the reason to keep closed socket in TIME_WAIT state is to ensure that delayed packets reached to the corresponding socket. Different operating system has different default time to keep sockets in TIME_WAIT state, in Linux it's 60 seconds, while in Windows is 4 minutes. Remember longer the timeout, longer your closed socket will keep file handle, which increase chances of java.net.SocketException: Too many files open exception

SQL Query to find all table names on database in MySQL and SQL Server Examples

How do you find names of all tables in a database is a recent  SQL interview questions asked to one of my friend. There are many ways to find all table names form any database like MySQL and SQL Server. You can get table names either from INFORMATION_SCHEMA or sys.tables based upon whether you are using MySQL or Sql Server database. This is not a popular question like when to use truncate and delete or correlated vs noncorrelated subquery which you can expect almost all candidate prepare well but this is quite common if you are working on any database e.g. MySQL. In this SQL tutorial we will see examples of getting names of all tables from MySQL and SQL Server database. In MySQL there are two ways to find names of all tables, either by using "show" keyword or  by query INFORMATION_SCHEMA. In  case of SQL Server or MSSQL, You can either use sys.tables or INFORMATION_SCHEMA to get all table names for a database. By the way if you are new in MySQL server and exploring it , you may find this list of frequently used MySQL server commands handy.

Monday, August 12, 2013

Swing is not thread-safe in Java - What does it mean? Event Dispatcher, SwingWorker, Multithreading and Best Practices

Couple of my reader ask question, what does it mean by Swing is not thread-safe and How does it affect coding in Swing GUI application? This post is an effort to help those readers and several other programmers to understand Swing and thread-safety in a bit more detailed way. To keep it simple, let's revise what does it mean by being thread-safe? We say an object is thread-safe, if we can call it's method, which can change it's state, from multiple thread at same time. To give you an example, java.lang.String is a thread-safe class, which means you can call any method e.g. substring(), toUpperCase() or toLowerCase() from multiple threads. By the way, String is thread-safe because it's immutable. Let's come back to Swing now, Core part of Swing is made up of different GUI component e.g. JLable, JPanel, JCombobox etc. All these components are not thread-safe, which means you can not call methods of this components e.g. JLable.setText("new title") from any thread, other than Event Dispatcher Thread(EDT)

Saturday, August 10, 2013

How to parse String to Float in Java | Convert Float to String in Java - 3 Examples

float and double are two data type which is used to store floating point values in Java and we often need to convert String to float in Java and sometimes even a Float object or float primitive to String. One thing, which is worth remembering about floating point numbers in Java is that they are approximate values, a float value 100.1f may hold actual value as 100.099998, which will be clear when we have seen examples of converting float to String and vice-versa. By the way, It's easy to parse String to float and vice-versa, as rich Java API provides several ways of doing it. If you already familiar with converting String to int or may be String to double in Java, then you can extend same techniques and method to parse float String values. key methods like valueOf() and parseInt(), which is used to parse String to float are overloaded for most primitive data types. 

Thursday, August 8, 2013

Difference between ON HOLD and ON ICE jobs in Autosys - Interview Question

Autosys is job management and scheduling tool and widely used in Investment banks on UNIX or Linux based environment. Autosys is used to start Java process, takes backup of log files, stop Java process, cleaning and purging database and will all sort of housekeeping jobs in Linux environment. Autosys system is made of Autosys server and Autosys clients, each server or box, which has services scheduled by autosys, requires autosys client to be install on that. One of the key advantages of Autosys is that one job can depend upon another job, and can execute, depending upon, success and failure of parent job. Though Java developers are not asked a lot of interview questions, you might expect few of them during your interview with Wall Street banks, Brokers or Financial Institution, which uses autosys.

Tuesday, August 6, 2013

Difference between SubStr vs SubString method in JavaScript - Tutorial Example

JavaScript provides two similar looking String manipulation function, substr and substring, though both are used to get substring from an String, there is a subtle difference between substring and substr method in JavaScript. If you look at there signature, both substr(to, length) and substring(to, from) both takes two parameters, but substr takes length of substring to be returned, while substring takes end index (excluding) for substring.This main difference will be more clear when we will see couple of examples of using substr and substring in JavaScript code. By the way this is also a good JavaScript question and frequently asked to web developers during HTML, CSS and JavaScript interviews, along with how to prevent multiple submission of form data. Because of extensive uses of String, this knowledge is not only important from interview point of view but also from development point of view. It also helps to reduce subtle bugs in JavaScript code, which is introduce because of incorrect use of substr or substring method.

Monday, August 5, 2013

Difference between Clustered Index and Non Clustered Index in SQL Server - Database Interview Question

In SQL Server database there are mainly two types of  indexes, Clustered index, and Non-Clustered index and the difference between Clustered and Non Clustered index is very important from SQL performance perspective. It is also one of the most common SQL Interview question, similar to the difference between truncate and delete,  primary key or unique key or  correlated vs non-correlated subquery. For those, who are not aware of benefits of Index or why we use an index in the database, they help in making your SELECT query faster. A query with an index is sometimes 100 times faster than a query without an index, of course depending upon how big your table is, but, you must index on columns which are frequently used in WHERE clause of the SELECT query, or which forms a major criterion for searching in the database. For example in Employee database, EmployeeId or  EmployeeName are common conditions to find an Employee in the database. 

Friday, August 2, 2013

2 Example to Merge or Join Multiple List in Java - Tutorial

Sometimes, we need to merge multiple lists into one before performing any operation, say Iteration or transformation. It's quite common to merge two lists, or combine them into a bigger list and there are multiple ways to do it. In this article, we will take a look at two simple way to join two lists in Java, you can further extend that idea to join any number of List or it's implementation e.g. ArrayList or LinkedList in Java. One way to merge multiple lists is by using addAll() method of java.util.Collection class, which allows you to add content of one List into another List. By using addAll() method you can add contents from as many List as you want, it's best way to combine multiple List. One thing to remember is that it also preserves the order on which objects from List are added, it actually appends at the end of the collection. So if you add List1 and than List2, content of List1 will come before elements of List2. You can even use this technique to combine multiple List into a Set to remove any duplicates

Thursday, August 1, 2013

Difference between WHERE vs HAVING clause in SQL - GROUP BY Comparison with Example

What is difference between WHERE and  HAVING clause in SQL is one of the most popular question asked on SQL and database interviews, especially to beginners. Since programming jobs, required more than one skill, it’s quite common to see couple of SQL Interview questions in Java and .NET interviews. By the way unlike any other question, not many Java programmers or dot net developers, who is supposed to have knowledge of basic SQL, fail to answer this question. Though almost half of the programmer says that WHERE is used in any SELECT query, while HAVING clause is only used in SELECT queries, which contains aggregate function or group by clause, which is correct. Though both WHERE and HAVING clause is used to specify filtering condition in SQL, there is subtle difference between them. Real twist comes into interview, when they are asked to explain result of a SELECT query, which contains both WHERE and HAVING clause, I have seen many people getting confused there. 

Wednesday, July 31, 2013

JQuery Selectors Examples to find elements in DOM - ID, Class, Element, Descendent, Child, Multiple and Pseudo Selector

jQuery selectors are like CSS Selectors, which allows you to find or select an element from DOM tree. When an HTML pages loaded in a browser like Chrome, Firefox or Internet Explorer, the browser creates a tree-like structure is known as Document Object Model or DOM. JavaScript and jQuery allow you to play with this DOM i.e. selecting elements from DOM, traversing through DOM, going from one element to another, selecting a list of elements from DOM, adding or removing elements from DOM etc. In order to apply most of the jQuery function, available in the jQuery object, we first need to select HTML elements or tags, on which we want to apply those function, jQuery selector allows you to choose those elements. There are many JQuery selectors e.g. ID selector, class selector or element selector, which provides the capability to choose only elements you need. In this JQuery tutorial, we will take a look at these jQuery selectors, and simple example to learn how to use them. 

Monday, July 29, 2013

2 Books to Prepare Oracle Java Certification Exams - OCA and OCP Java SE 7 OCPJP 7

There was a time when Sun Certification was very hot and programmers feel proud on being Sun Certified Java professional(SCJP). After Oracle took over Sun in early 2010, it changed names of all the examination from SCJP to OCPJP or OCJP, and now OCA and OCP for Java SE 7. I see there is a lot of confusion among certification nowadays, but essentially they are of the same level at previous SCJP. Since Java gets new language feature with every new release, subsequently a new certification title is introduced. I am not agreed with upgrading your Java certification with every release, it doesn't make much sense to me, but many programmers prefer to get certified and keep it updated.

Friday, July 26, 2013

How to bypass Websense Internet Filter at Office, School to Access Programming WebSites

Recently one of my readers emailed me that he can not access any .blogspot or .wordpress domain from his office because Websense is blocking them as personal blogs category. Since we techies, often relied on personal technical experience, tips shared by fellow developers for our work, this feels really annoying, but same time it's difficult to convince Websense guys or local Websense security team to not put such restriction. I was thinking about alternative and done some research on the internet, which tells me that you can bypass Websense filter at school or office by using proxy sites, but this idea doesn’t seem good to me, as they may contain some unwanted piece of crap, which is not good for anyone's computer. Also, if you are working for a decent size company, there is good chance that those proxy sites will also be blocked by Websense. This leaves no option at all to access any technical or programming blog, hosted on a free domain like .blogspot or .wordpress domain. That’s why some blogger prefers to have their own domain name than relying on blogger or WordPress.

Wednesday, July 24, 2013

File Upload Example in Java using Servlet, JSP and Apache Commons FileUpload - Tutorial

Uploading File to the server using Servlet and JSP is a common task in Java web application. Before coding your Servlet or JSP to handle file upload request, you need to know a little bit about File upload support in HTML and HTTP protocol. If you want your user to choose files from the file system and upload to the server then you need to use <input type="file"/>. This will enable to choose any file from the file system and upload to a server. Next thing is that form method should be HTTP POST with enctype as multipart/form-data, which makes file data available in parts inside request body. Now in order to read those file parts and create a File inside Servlet can be done by using ServletOutputStream. It's better to use Apache commons FileUpload, an open source library. Apache FileUpload handles all low details of parsing HTTP request which conform to RFC 1867 or "Form-based File upload in HTML” when you set form method post and content type as "multipart/form-data".

Tuesday, July 23, 2013

How to create Thread Pools using Java 1.5 Executor Framework - Example Tutorial

Java 1.5 introduced Thread pool in Java in the form of Executor framework, which allows Java programmer to decouple submission of a task to execution of the task. If you are doing server side programming in Java than Thread pool is an important concept to maintain scalability, robustness, and stability of the system. For those, who are not familiar with thread pool in Java or concept of thread pool here is one liner, Thread pool in Java is a pool of worker threads, which is ready to perform any task given to them, mostly in the form of implementation of Runnable or Callable interface. Since Java supports multithreading in programming language itself, it allows multiple threads to run concurrently and perform parallel processing of the task. In this article, we will learn following things about thread pool in Java :
  1. What is Thread pool in Java?
  2. Why do we need Thread pool in Java ?
  3. What is Executor framework in Java 5?
  4. How to create fixed size thread pool using Executor framework in Java?
  5. Benefits of using Thread Pool in Java?

Thursday, July 18, 2013

How to Configure HTTPS (SSL) in Tomcat 6 and 7 Java Web Server

Setting SSL (Secure Socket Layer) in Tomcat is often a requirement, especially while developing  secure web application, which requires access over https protocol. Since Tomcat web server doesn't provide SSL settings by default, you need to know how to configure SSL in tomcat, and even worse it varies between different tomcat versions. for Example SSL setup which works on tomcat 6, doesn't work as it is in tomcat 7. In this article we will see, how to configure tomcat for https in both tomcat 6 and 7. For those programmers who are not very familiar with SSL and https here is a quick overview of SSL, certificates and https, and I suggest reading that article to get better understanding of How SSL works and How websites are accessed security over internet.

Wednesday, July 17, 2013

10 Things Every Java Programmer Should Know about String

String in Java is very special class and most frequently used class as well. There are lot many things to learn about String in Java than any other class, and having a good knowledge of different String functionalities makes you to use it properly. Given heavy use of Java String in almost any kind of project, it become even more important to know subtle detail about String. Though I have shared lot of String related article already here in Javarevisited, this is an effort to bring some of String feature together. In this tutorial we will see some important points about Java String, which is worth remembering. You can also refer my earlier post 10 advanced Java String questions to know more about String

Though I tried to cover lot of things, there are definitely few things, which I might have missed; please let me know if you have any question or doubt on java.lang.String functionality and I will try to address them here.

Monday, July 15, 2013

Difference between linked list and array data structure in Java Programming

Array and linked list are two fundamental data structure in programming world. Almost all programs use Array in some form or other, which makes it increasingly important to learn array and linked list. Difference between linked list and array data structure is also a popular data structure question, frequently asked in various programming job interview. This makes it even more important to learn and understand difference between an array and a linked list. Well there are lot of difference between these two starting from how they store data, to how you retrieve data from them. Main difference comes from the fact that array elements are stored in contiguous memory location, which makes it easy to retrieve them in quick time, while linked list elements are scattered through out memory, where one element knows address of other, it makes it hard to retrieve element from linked list in quick time. Some of the differences which we saw in ArrayList vs LinkedList also applicable at data structure level, because ArrayList is backed by array and LinkedList is internally backed by double linked list in Java. 

Wednesday, July 10, 2013

When to make a method static in Java

Making a method static in Java is an important decision . Though, static keyword is one of the fundamental concepts, many times programmers gets confused to make a particular method static or not. In Java programming, main motivation for making a method static is convenience. You can call a static method without creating any object, just by using it's class name. So if you need a method, which you want to call directly by class name, make that method static. Utility classes e.g. java.lang.Math or StringUtils, are good examples of classes, which uses static methods. Before making a method static, you should look into limitation of static methods as well, as you can not override static method in Java

Monday, July 8, 2013

Top 5 JQuery books for Beginners and Web developers - Best of lot

jQuery is a open source JavaScript library, which has completely changed the way, client side web development was done using HTML, CSS and JavaScript. With growing popularity of jQuery, it become imperative for web developers to learn and take advantage of jQuery and books are one of the best way to learn jQuery. In this article, I am going to share you top 5 jQuery books from my personal collection, which I have looked and researched before purchasing my first book on jQuery, Head First JQuery. Since I like to follow one book at a time, I didn't bother to look into another must read book, JQuery in Action, until I have finished former. After finishing my first book on jQuery, I am quite comfortable with jQuery magic, which means doing things like DOM Selection, traversal, DOM manipulation based on CSS selector, animation and cool effects, and responding to use actions (event handling) in couple of lines. 

Thursday, July 4, 2013

How SSL, HTTPS and Certificates works in Java web applications

Basic knowledge of SSL, HTTPS and Certificates are must for any Java programmer, especially who is working in financial and security sensitive applications, which are accessed over internet. In this article, I am giving you an overview of these three key concept and How SSL, HTTPS and certificates work together, to provide secure communication between client and server. Security is major concern while developing web application, which is accessible using HTTP protocol. Since HTTP protocol transfer data in plain text format, its not safe for transferring sensitive information like username, password, social security number (SSN) or credit card details for online shopping. HTTP protocol, also doesn't guarantee that a website, you are communicating is the one who claims i.e. if URL redirection is enable than instead of genuine website you may be routed to malicious websites and HTTP can't prevent or alert you.

Tuesday, July 2, 2013

Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization

Authentication and Authorization is integral part of any Java enterprise or web application. Since most of the company uses LDAP Active directory for authentication, authorization and Role based access control (RBAC), it's good to know How to implement Role based access control using Spring MVC and Spring Security. This is the second part of my articles on using Spring Security for authentication and authorization in Spring MVC based Java application. In last part, we have learned about doing LDAP authentication against Windows active directory, and in this Spring Security tutorial, we will learn How to map LDAP groups to authorities for implementing Role based access control or authorization. If you are developing an application, whose access is controled by adding user to a particular LDAP group, then you need a mechanism to load those LDAP group after successful authentication. Spring Secuirty uses GrantedAuthority class for holding all roles for a particular user. 

Thursday, June 27, 2013

10 Java Exception and Error Interview Questions Answers

You will always see some interview questions from Exception and Error handling in core Java Interviews. Exception handling is an important aspect of Java application development and its key to writing robust, stable Java programs, which makes it natural favorites on interviews. Questions from Error and Exception in Java mostly based on the concept of Exception and Error in Java, How to handle Exception , best practices to follow during Exception handling etc. Though multithreading, garbage collection, JVM concepts and questions from object oriented design rules these interviews, you should always expect and prepare some questions on effective error handling.

Tuesday, June 25, 2013

5 books to learn Object Oriented Programming and Design patterns - Best of lot

Knowledge of Object oriented design principle and the various design pattern is a must for any Java developer. As I said earlier on 10 OOPS and SOLID design principles, coding without knowing these principles are like trying to learn a language without knowing alphabets. By the way, there are several books written on Object-oriented design principles, design patterns, and best practices, but only a few of them provides what they claim. There are two things here, design principles and design patterns, one is basic and other is best practice built on that basic. One should first learn Object-oriented principles and then learn design patterns to see how those principles are used to solve day to day problems. 

Tuesday, June 18, 2013

How to Add Two Integer Numbers without using Plus + or ++ Arithmetic Operator in Java - Recursion example

In this article, we will take a look at another interview question about adding two numbers, but without using + or ++ operator. Interview starts with a simple statement, Can you write a function to add two numbers (integers) without using + or plus arithmetic operator in Java? If you are good at maths, it wouldn’t take more than a second to say that, we can use subtraction or - operator to add two numbers because a-(-b)== a+b. Well, that’s correct, but real question starts when interviewer quickly points out that, you can not use any arithmetic operator including +,-,*,/++ or --. Programming and Coding questions are an integral part of any Java interview. You should always expect a couple of questions like this, e.g. swapping two numbers without using a temp variable. If you have been giving interviews, then you know that it will eventually come downs to the bitwise operator in Java. 

Tuesday, June 11, 2013

How to Generate MD5 checksum for Files in Java

MD5 checksums are good to verify the integrity of files and It's easy to generate MD5 checksum in Java. Java provides a couple of ways to generate the MD5 checksum for any file, you can either use java.security.MessageDigest or any open source library like Apache commons codec or Spring. All 3 ways we have seen in our earlier article about generating the MD5 hash for String is also applicable to generate the MD5  checksum for any file. Since most of the md5() or md5Hex() method takes byte[], you can simply read bytes from InputStream or pass to these md5 methods. Apache commons codec from version 1.4 also provides an overloaded method for accepting InputStream, which makes generating checksum very easy in Java. For those who are not familiar with checksum, it's a fixed-size datum generated from a block of data to detect any accidental change in data. 

Thursday, June 6, 2013

How to get current URL, parameters and Hash tag using JQuery and JavaScript

While dealing with current URL, many time you want to know what is the current URL path, What are the parameters, and what is the hashtag on URL. The hash tag is pretty important if you are implementing tab structure using HTML and JQuery. To avoid confusion, let's take an example of URL: http://javarevisited.blogspot.com/2013/01/top-5-java-programming-books-best-good.html#ixzz2PGmDFlPd , in this example ixzz2PGmDFlPd, is a hash tag. Now, both JavaScript and JQuery provides a convenient way to retrieve current URL in the form of window.location object. You can use various properties of the window.location JavaScript object e.g. window.location.href to get complete URL, window.location.pathname to get the current path, and window.location.hash to get a hash tag from current URL. If you like to use JQuery then you can get a window.location as JQuery object and retrieve relevant properties using attr() function. 

Tuesday, June 4, 2013

5 Reasons to Use Composition over Inheritance in Java and OOP

Favor composition over inheritance is a one of the popular object-oriented design principles, which helps to create flexible and maintainable code in Java and other object-oriented languages. Many times I have seen people suggesting use composition instead of inheritance, in fact, my favorite books like Head first Design Patterns also advocates this design principle. Head first books have its own way of explaining, why composition is better than inheritance and though its long its quite interesting and informative. It was the first chapter of this book, which helped me a lot on understanding this key OOPS concept. In this Java and OOPS tutorial, I have tried to summarize my experience around composition and inheritance in two main category, first, difference between composition and inheritance and second, when to use Composition over inheritance in Java. 

Monday, June 3, 2013

How to find CPU and Memory used by Java process in Solaris – prstat command example

We often need to find CPU and memory utilization of a particular Java process in order to get some performance stats, capacity planning or just to understand the current load on the system. Performance monitoring and testing is an integral part of any Java application development, especially if you are working in high-frequency trading space. In order to fix a performance problem, you have to find them first and knowledge of right tools and commands helps there. One of the primary cause of poor application performance is it Java or any other process is exhaustion of important resources like CPU and memory. Monitoring CPU and memory utilization of your Java process give you some useful insight like what is the normal memory and CPU utilization, when are you getting spikes in CPU and memory consumption. If  heap memory is constantly increasing over time than it’s an indication that your Java application may have a memory leak. 

In this Java performance tutorial, we will learn about two most common Solaris commands prstat and pmap to find CPU and memory utilization of Java process. prstat is a process monitoring tool easily available in any Solaris systems including SPARC and x86 boxes, which provides useful statics of CPU and memory utilization of a process. 

For other systems e.g. windows you can use windows task manager for CPU monitoring and Linux you can use top command for same purpose. By the way, you can also check out Java performance by Charlie Hunt and Binu John, it is immensely helpful for Java performance monitoring and tuning. This is the book, which gives you right kind of tools and knowledge required to find performance stats for Java application.

Thursday, May 30, 2013

How to Check if Integer Number is Power of Two in Java - 3 examples

How to check if an integer number is a power of 2 in Java is one of the popular programming interview question and has been asked in many interviews. Surprisingly, this problem which looks simple enough to answer, doesn't turn out that simple if for many developers. Many Java programmers, both freshers and less experienced,  struggle to write code for a function, which can check if number is power of 2 or not. There could be many different reasons for that, but it’s expected to at least come up with brute force solution. For those who are familiar with bitwise operators in Java , how positive and negative numbers are represented in binary format, this exercise is quite easy. Since negative numbers are represented as 2's complement value in Java, you can easily find if any number is power of 2 or not by looking at its bit pattern. Remember checking for power of two is different than checking if number is even or odd, that’s another thing to note. A number can be even, but it’s not necessary to be a power of  two, e.g. 6 is even but it’s not a power of two.

Tuesday, May 28, 2013

Java Tips and Best practices to avoid NullPointerException in Java Applications

A NullPointerException in Java application is best way to solve it and that is also key to write robust programs which can work smoothly. As it said “prevention is better than cure”, same is true with nasty NullPointerException. Thankfully by applying some defensive coding techniques and following contract between multiple part of application, you can avoid NullPointerException in Java to a good extent. By the way this is the second post on NullPointerException in Javarevisited, In last post we have discussed about common cause of NullPointerException in Java and in this tutorial,  we will learn some Java coding techniques and best practices, which can be used to avoid NullPointerException in Java. Following these Java tips also minimize number of !=null check, which litter lot of Java code. As an experience Java programmer, you may be aware of some of these techniques and already following it in your project, but for freshers and intermediate developers, this can be good learning. By the way, if you know any other Java tips to avoid NullPointerException and reduce null checks in Java, then please share with us.

Friday, May 24, 2013

10 XSLT or XML, XSL transformation Interview Questions and Answers

XSLT stands for XML style sheet transformation and it as XML technology used to transform one XML into another XML or HTML format.  XML and XSLT interview questions are commonly asked Java developers, who happen to use XML in their project and mentioned XSLT as a key skill in their resume. Given XML’s popularity as data transfer protocol, many systems in middle and back office space uses XML messages to transfer trade details, for example, Bookings, Settlement, and Confirmation system use it as a data exchange protocol. Since each of this system performs some normalization, enrichment, and transform on incoming trade message, they use XSLT for that transformation. XSLT is rich, powerful and given its support in Java and several other programming languages, it comes the natural choice of XML transformation. What you need to is to write XSL files, also known as XML style sheet to specify your transformation rule and then XSLT engine will transform each incoming XML documents as per your XSL file.