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.

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 in production. 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.

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.

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. 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.

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). 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.

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.

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 advantage 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 lot of interview questions, you might expect few of them during your interview with Wall Street banks, Brokers or Financial Institution, which uses autosys. This is more important for support people, and must know if you are applying for a production support role in Investment banks, and often asked along with UNIX Interview questions and SQL query interview questions, which are key technology skills for support person.. In this article, we will take a look at one of the important and frequently asked Autosys Interview questions, difference between ON HOLD and ON ICE jobs. Though both ON HOLD and ON ICE command stops a job from executing, difference comes into picture, when they are OFF HOLD and OFF ICE. Before going into differences between them, let's see What is ON_HOLD and ON_ICE job status in 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 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 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 index in database, they help in making your SELECT query faster. A query with index is sometime 100 times faster than a query without index, of course depending upon how big your table is, but, you must index on columns which are frequently used in WHERE clause of SELECT query, or which forms major criterion for searching in database. For example in Employee database, EmployeeId or  EmployeeName are common conditions to find an Employee in database. As I said, there can be either clustered index or non clustered index in database, former is used to decide how data is physically stored in disk and that's why there can be only one clustered index in any table. In this article, we will explore more about both of this indexes and learn some key difference between clustered and non clustered index from interview and performance perspective. 

Friday, August 2, 2013

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

Sometime, we need to merge multiple list into one before performing any operation, say Iteration or transformation. It's quite common to merge two list, 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 list 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 list 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 preservers the order on which objects from List are added, it actually appends at the end of 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. Another way of merging ArrayList is using Apache Commons Collection, Apart from several goodies, like creating union of Set in Java,  it provides a ListUtils class with a union method, which can be used to create union of two List in Java. Result of previous operation and this is same, It also preservers the order and appends elements of second List after elements of first List.

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. Key point, which is also main difference between WHERE and HAVING clause in SQL is that, condition specified in WHERE clause is used while fetching data (rows) from table, and data which doesn't pass the condition will not be fetched into result set, on the other hand HAVING clause is later used to filter summarized data or grouped data. In short if both WHERE and HAVING clause is used in a SELECT query with aggregate function or GROUP BY clause, it will execute before HAVING clause. This will be more clear, when we will see an example of WHERE, HAVING, JOIN and GROUP BY clause together.