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

Saturday, May 25, 2013

Which Programming Book would you buy if you were given 100$ to spend?

Hello Guys, it's time to take an hypothetical question in Javarevisited. Which programming book, would you love to buy, if you are given 100$ to spend? I know, when it comes to buying, people want to worth of there money, and that's why I am posting this question to you guys. Suppose you are looking some books in a bookstore and suddenly salesman comes and say, at this particular minute, we are giving you 100$ FREE to buy any programming book. Now you just have 10 minute to complete your purchase and take away those awesome Java books absolutely for FREE, what are the books you are going to buy?

Friday, May 24, 2013

10 XSLT or XML, XSL transformation Interview Questions and Answers for Java Programmers

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 to Java developers, who happen to use XML in there project and mentioned XSLT as key skill in there 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 uses 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 those transformation. XSLT is rich, powerful and given it’s support in Java and several other programming language, it comes 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 than XSLT engine will transform each incoming XML documents as per your XSL file. Though, XSLT is rich, it’s can also be very complex for Java programmers, who are used to procedural style of coding, as XSLT uses recursion a lot. So if you are a Java programmer, who have used XSLT or going for a Job interview, where XSLT is a key skill, you better be prepare with some popular XSLT interview questions, In this article, I am sharing my list of XSLT questions, which is collected from internet, friends and colleagues and frequently asked as part of XML Interview questions.

Monday, May 20, 2013

SED Command Examples in UNIX and Linux, Find and Replace using Regular Expression

SED command in UNIX  is stands for stream editor and it can perform lot's of function on file like, searching, find and replace, insertion or deletion. Though most common use of SED command in UNIX is for substitution or for find and replace. By using SED you can edit files even without opening it, which is much quicker way to find and replace something in file, than first opening that file in VI Editor and then changing it. In this SED command tutorial we will see some practical examples of SED command in UNIX based systems e.g. Linux. I must say having a good grip on find, grep, sort, vi editor and SED can take you next level of UNIX and Linux working experience. These are very powerful UNIX command and helps with lot of different tasks in server. By the way we will use following text file for our SED common example. As I have said before, best way to learn any UNIX command is to use them in your day to day task, and a good example is a good start. This file contains details of some popular android and iPhone smartphones, e.g. Model, company, price etc, separated by colon. You can also use any CSV file for this example.

Friday, May 17, 2013

How to Generate Random Numbers in Java between Range - Example Tutorial

In software development and programming world we often needs to generate random numbers, some time random integers in a range e.g. 1 to 100 etc. Thankfully, Random number generation in Java is easy as Java API provides good support for random numbers via java.util.Random class, Math.random() utility method and recently ThreadLocalRandom class in Java 7, along with more popular features like String in Switch and ARM blocks. While random() method seems most convenient way of generating randoms in Java it only return random doubles, on the other hand by using Random,  you can generate pseudo-random integer, floating point numbers e.g. double and even random boolean values. In this article Java tutorial, we will see how to generate random numbers in Java, examples to generating random integers and real numbers, and random numbers within a range e.g. between 1 to 6. we will also explore difference between Math.random() and java.util.Random class in Java.

Tuesday, May 14, 2013

Difference between Abstract class vs Interface in Java and When to use them

When to use interface and abstract class is one of the most popular object oriented design questions and almost always asked in Java, C# and C++ interviews. In this article, we will mostly talk in context of Java programming language, but it equally applies to other languages as well. Question usually starts with difference between abstract class and interface in Java, which is rather easy to answer, especially if you are familiar with syntax of Java interface and abstract class. Things start getting difficult when interviewer ask about when to use abstract class and interface in Java, which is mostly based upon solid understanding of popular OOPS concept like Polymorphism, Encapsulation, Abstraction, Inheritance and Composition. Many programmer fumbles here, which is natural because most of them haven't gone through real system design process and haven’t seen the impact of choosing one over other. Repercussion of design decisions are best known during maintenance phase, a good design allows seamless evolution while maintaining a fragile design is nightmare. As I have said previously, some time object oriented design interview questions also helps to understand a topic better, but only if you are willing to do some research and not just mugging the answer. Questions like when to use abstract class and interface falls under same category. In order to best understand this topic, you need to work out some scenarios, examples etc. It's best to get this kind of knowledge as part of your work but even if you don't get there, you can supplement them by reading some good books like Head First design pattern and doing some object-oriented software design exercises. In this article, we will learn difference between abstract class and interface in Java programming language and based upon our understanding of those differences, we will try to find out some tips and guidelines to decide when its better to use abstract class over interface or vice-versa.

Monday, May 13, 2013

How to Find if Linked List contains Loops or Cycles in Java - Coding Question

Write a Java program to check if a linked list is circular or cyclic,  and how do you find if a linked list contains loop or cycles in Java are some common linked list related data structure interview questions asked in various Java Interviews. This is some time asked as follow-up question of basic linked list questions like inserting element at beginning, middle and end of linked list or finding length of linked list. In order to solve linked list related algorithmic question in Java, you need to be familiar with concept of singly linked list, doubly linked list and circular linked list. Until stated specifically, most questions are based on singly linked list. For those who are not familiar of linked list data structure, its a collection of nodes. Each node contains two parts data and address, where address part points to another node in linked list. Last node of linked list, often referred as tail points to null. Also a singly list can only move in one direction, towards end. Now, let's come back to this question. Good thing about this question is that, it can also be solved by using two pointer approach discussed in How to find middle element of linked list in single pass. If a linked list contains a loop or cycle it is known as circular or cyclic linked list. As I said we can use two pointer approach to check if a linked list is circular or not.

Friday, May 10, 2013

Difference between LEFT and RIGHT OUTER Joins in SQL - MySQL Join example

There are two kinds of OUTER joins in SQL, LEFT OUTER join and RIGHT OUTER join. Main difference between RIGHT OUTER join and LEFT OUTER join, as there name suggest, is inclusion of non matched rows. Sine INNER join only include matching rows, where value of joining column is same, in final result set, but OUTER join extends that functionality and also include unmatched rows in final result. LEFT outer join includes unmatched rows from table written on left of join predicate. On the other hand RIGHT OUTER join, along with all matching rows, includes unmatched rows from right side of table. In short result of LEFT outer join is INNER JOIN + unmatched rows from LEFT table and RIGHT OUTER join is INNER JOIN + unmatched rows from right hand side table. Similar to difference between INNER join and OUTER join, difference between LEFT and RIGHT OUTER JOIN can be better understand by a simple example, which we will see in next section. By the way joins are very popular in SQL interviews, and along with classic questions like finding second highest salary of employee, Inner join vs outer join or left outer join vs right outer join is commonly asked.

Thursday, May 9, 2013

Migrating SQL Query from Oracle to SQL Server 2008 or Sybase

Oracle and Microsoft SQL Server are very different than each other and if you are migrating SQL queries or database, tables from Oracle 11g database to Microsoft 2008 SQL server than you are bound to face some issues. Main reason of these porting issues are features, which are supported and exists in Oracle database, but not available in Microsoft SQL Server 2008 like SEQUENCE, Order by clause in sub queries and derived tables, derived table without name etc. I am sure there are few more and it will surface based upon different database objects you are using in your tables and queries. On other hand SQL Engine for SQL Server and Sybase are very much similar, at least syntactically, and if you are migrating queries from SQL Server to Sybase you can do that without much hassle, of course there will be slight changes but not as much like Oracle. So if you are migrating from Oracle to Sybase or SQL Server its most likely same job and you should first start with either SQL Server or Sybase ASE and than later migrate them from each other. In this Oracle and SQL Server tutorial we will see couple of examples, where Oracle and SQL Server are different and how to change those SQL queries so that it can run on Microsoft SQL Server. By the way I have also written couple of post on queries like 10 ways to use SQL SELECT queries and Don’t delete, truncate it. If you like reading more on SQL queries than those are for you.

Wednesday, May 8, 2013

How to convert List of Integers to int array in Java - Coding Tips

So, you have a List of Integers and you want to convert them into int array? Yes you read it write, not on Integer array but int array. Though in most practical purpose, Integer array can be used in place of int[] because of autoboxing in Java, you still need an int[] if your method accepts it. In Java, you can not type cast an Integer array into int array. Many Java programmer think about toArray() method from java.util.List to convert a List into Array, but unfortunately toArray() is useless in most of times. It doesn't allow you to convert List into primitive arrays. Though you can convert List of Integers to array of Integers, but not array of primitive int. This is true for List of all wrapper class e.g. List of Float, Double, Long, toArray() method can return array of wrapper class but not primitives. After looking into Java Collection API, It seems that only traditional for loop or foreach can help, which involves iterating over Integer array and storing them into int[], but fortunately, I came across Apache Commons ArrayUtils class. ArrayUtils can do this work for us, It has several overloaded methods to convert Object arrays into primitive arrays. For example, you can convert an array of Double i.e. Double[] to primitive double array e.g. double[]. This example once again reinforced my thinking to include Apache Commons lang and Google's Guava by default in any Java project, they are rich and effectively complement standard JDK library.

Tuesday, May 7, 2013

10 Hibernate Interview Questions and Answers for Java J2EE Programmers

Hibernate Interview Questions are asked on Java J2EE Interviews, mostly for web based enterprise application development role. Success and acceptability of Hibernate framework on Java world has made it one of the most popular Object Relational Mapping (ORM) solution in Java technology stack. Hibernate frees you from database specific coding and allows you to focus more on utilizing powerful object oriented design principle to implement core business logic. By using Hibernate you can switch between database rather easily and also take advantage of out of box caching facilities provided by Hibernate, in terms of second level cache and query cache. As you know most of Java interview not only contains questions from core Java, but also from other Java framework e.g. questions from Spring Framework or Struts interview questions, based upon projects requirements. Its good to prepare both Spring and Hibernate questions quite well, if you are going to work on a project which uses Hibernate as ORM. Check JD or Job description ,and if you see word Hibernate anywhere, get ready to face some Hibernate questions.

Monday, May 6, 2013

Java Mistake 3 - Using "==" instead of equals() to compare Objects in Java

In this part of Java programming mistakes, we will take a look on another common pattern, where programmers tend to use "==" operator to compare Objects, similar to comparing primitives. Since equality of object can be very different in physical and logical sense, and in case of domain objects it's mostly driven by business rules, comparing objects with "==" operator, introduces subtle bugs, which are hard to find. Difference between equals() and == operator,  one of the Java classics is also asked to find out if developer is familiar with this important concept or not. Using == operator only make sense when comparing primitives like int, or final constants like Enum. Though there is more involve in comparing two Enum, which you learn by following that link. One of the most common pattern of this mistake is is comparing two Strings with == operator, which we will see in this article. By the way this is third in series of common Java programming mistakes, and if you haven't read the previous two, you can read them here :

Thursday, May 2, 2013

Java Program to Find Sum of Digits in a Number using Recursion - Interview Question

Recently this question to asked was one of my reader, which inspired me to write this tutorial. There was usual check to solve this problem using both recursion and iteration. To be frank, calculating sum of digit of an integral number, is not difficult, but I have still seen quite a few programmers fumbles, even after providing hint in terms of division and modules operator. Key point here is to know how to use division and modules operator in Java. For this kind of exercise including reversing a number, where you need to find digits from a number, use division operator to remove right, and use modules operator or % to get right most digits. For example if you have number 1234 than 1234/10 will give you 123 i.e. right most digit 4 is removed, while 1234%10 will give you 4, which is the right most digit in that number. If you know this property, you can easily solve lots or problems which are related to reversing numbers e.g. checking if a number is palindrome or finding Armstrong numbers in Java.