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 same memory address, while default implementation of hashcode method return int and implemented as native method. Similar default implementation of toString() method, returns type of class, followed by memory address in hex String. It's advised to override these method, based upon logical and business rules e.g. String overrides equals to check equality of two String based upon content, we have also seen and example implementation of equals() and hashCode for custom classes. Because of there usefulness and usage, they are also very popular in various level of Java Interviews, and In this tutorial, I am going to shared some of the really interesting questions from equals() and hashCode() method in Java. This question not only test your concept on both method, but also gives an opportunity to explore them more.
Read more �

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 library, but in order to use it, you need to load into your webpage using standard HTML <script> tag. Based on whether your webpage is public accessible or for a organization, you can either choose to load 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>. jQuery site offers compressed and uncompressed copies of jQuery files, uncompressed file is good for development and debugging, but can slow down page loading if used in production. Compressed file saves bandwidth and improves performance inproduction. In this article, I am sharing couple of CDN URLs from where you can directly load jQuery files into your web page, this includes popular Google CDN, jQuery CDN and Microsoft CDN.
Read more �

Tuesday, August 20, 2013

Why use SLF4J over Log4J for logging in Java

Every Java programmers knows 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 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 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 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. Suppose if a project is already using log4j, and you included a library say Apache Active MQ, which has dependency on logback, another logging library, then you need to include them as well, but if Apache Active MQ uses SL4J, you can continue with your logging library, without pain of adding and maintaining new logging framework. In short SLF4J make your code independent of any particular logging API, which is good think for public API developers. Though idea of abstracting logging library is not new and Apache commons logging is already using it, but now SLF4J is quickly becoming an standard for logging in Java world. Let's see couple of more reason to use SLF4J over log4j, logback or java.util.logging.
Read more �

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(Comparatorcmp), 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 Listimplementation e.g. ArrayList, LinkedListor Vectorin Java.
Read more �

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. This also means, if you are running Tomcat, Weblogic, Websphere or any other web server in windows machine, you are more prone to this error than Linux based systems e.g. Solaris or Ubuntu. By the way this error is same as java.io.IOException: Too many files open exception, which is throw by code from IO package if you try to open a new FileInputStream or any stream pointing to file resource.
Read more �

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.
Read more �

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). In one word, Since Swing is not thread-safe, you can not update Swing components from any random thread, they are always updated using Event Dispatcher thread. This is in fact one of the most popular Java Swing Interview Question, with lot's of interesting follow-up e.g. If Swing is not thread-safe than how do you update components from other thread? and which methods of Swing API are thread-safe? etc. We will see answer of this question in next section.
Read more �

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 sometime 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 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. If you are particularly interested on rounding of float values, you can use RoundingMode and BigDecimal class, as float and double are always approximate values and comparing two float variable of same values may not always return true, that's why it's advised, not to use float for monetary calculation. In this Java tutorial, we will first see examples of parsing String to float in Java and later converting float to String objects. Remember, we will use float and Float, a wrapper class corresponding to float primitive, interchangeably because by using Java 1.5 autoboxing feature, they are automatically converted to each other, without any Java code. For those, who are still in Java 1.4 or lower version, then can use Float.floatValue() to convert Float wrapper object to float primitive.
Read more �

Friday, August 9, 2013

Liens pratiques de la semaine

Vous trouverez dans ce billet une s�lection de liens pratiques autour des technologies Java qui m'ont particuli�rement int�ress�es ces derni�res semaines. 

Eclipse
  • Un tutoriel tr�s simple sur la cr�ation d'une application Eclipse RCP avec E4.
  • Un billet de l'auteur du livre Eclipse 4 Plug-in Development by Example: Beginner�s Guide qui d�taille plein de choses autour de l'�criture et de la publication de son livre.
  • Un billet qui montre comment utiliser le syst�me d'�v�nements d'Eclipse 4 (EventBroker) sans l'injection de d�pendance.
  • Une solution qui montre comment utiliser le logger d'Eclipse 4 depuis une m�thode statique.
  • Un article qui montre comment utiliser le contr�leur de geste LeapMotion au sein d'une application Eclipse 4. A noter que cet article montre �galement comment cr�er ses propres annotations.
  • EScript est un langage de scripts pour Eclipse.
  • Un billet qui propose des classes utilitaires pour g�rer efficacement les agents de placement GridLayout et GridData.
  • Un tutoriel de d�marrage (Getting Started) pour EMFStore. Pour rappel ce projet permet de stocker, distribuer et collaborer � plusieurs avec des mod�les EMF (mod�les et instances).
  • Des statistiques de t�l�chargement sur la nouvelle version d'Eclipse Kepler : 1 million de t�l�chargement en 18 jours.
  • Un tutoriel qui propose de customiser l'apparence des mod�les EMF en utilisant EMF Client Platform.
  • Une astuce pour mettre en plein �cran une fen�tre d'une application Eclipse 4 RCP.
Java
  • Un article qui montre comment g�rer efficacement la Stack Trace c�t� client pour GWT.
  • docx4j est une biblioth�que Java pour manipuler les formats Microsoft Open XML.
NoSQL
  • Am�lioration du langage Cassandra CQL pr�vue pour Cassandra 2. J'ai not� principalement le support des triggers et les alias au niveau des SELECT.
Divers
  • Biblioth�que JavaScript qui permet de mettre en surbrillance le texte du code de plus de 54 langages.
  • ReaderIsDead ou ZombieReader est une initiative permettant de faire revivre Google Reader. De mon c�t� je suis pass� � Feedly. Je retrouve pratiquement tous les services de Google Reader except�s la cr�ation des blogrolls.
  • BZR Player est un lecteur Audio qui g�re une multitude de formats.
  • Un historique li� � l'univers Lego. Impressionnant la machine � r�soudre les Rubik's Cube.
  • S'il y a bien une application � installer sous Windows, c'est Clover. Cet utilitaire permet d'ajouter la notion d'onglets � votre explorateur Windows.
  • WinDirStat permet de connaitre l'occupation de vos r�pertoires. Il affiche l'information sous forme de Map.