SQLServerException: The index 58 is out of range - JDBC

I was executing a stored procedure against SQL SERVER 2008 database from Java program using CallableStatement, but unfortunately, I was getting following error "SQLServerException: The index 58 is out of range". Since I am passing a lot of parameters I thought that something is wrong with a number of parameters I was passing to the stored proc. My stored procedure had 58 INPUT parameters, as soon as I removed the 58th INPUT parameter the error goes away, which confirmed my belief that SQL SERVER supports a maximum of 57 INPUT parameters in stored procedure via JDBC. This  seems the really significant limitation, especially for big tables and I was thinking that It's more likely that 58 is not the actual limit and I might have missed something.

Producer Consumer Solution using BlockingQueue in Java

Producer Consumer problem is one of the classic multi-threading problems in computer science and the multi-threading world. It's tricky because it involves inter-thread communication, but it's important because most of the multi-threading problems fits into this category. There are many ways to solve producer consumer problem in Java e.g. you can solve this by using wait() and notify() method, as discussed here, or you can use the Semaphore to solve this problem. In this article, you will learn a third way to solve the producer-consumer problem by using the BlockingQueue in Java. It is arguably the simplest way to solve this problem in any programming language because blocking queue data structure not only provides storage but also provides flow control and thread-safety, which makes the code really simple. Brian Goetz has also explained this key class and pattern in his classic Java Concurrency in Practice book, a must read for serious Java developers.

Difference between Thread.start() and Thread.run() method in Java?

If you remember, a Thread is started in Java by calling the start() method of java.lang.Thread class, but if you learn more you will find out that start() method internally calls the run() method of Runnable interface to execute the code specified in the run() method in the separate thread. Now the question comes, why can't you just call the run() method instead of calling the start() method because anyway start() is calling the run()? This is one of the tricky multi-threading question you will find on Java interviews. The trick here is that, when you directly call the run() method than the code inside run() method will not be executed on a new thread, instead it will be executed on the same thread. On the other hand, when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method. This is one of the fundamental of threading in Java, which is often get overlooked by Java developers unless you have read book like Java Threads By Scott Oaks, which explains every key multi-threading concept and thread basics in good detail.

Top 3 Free Struts Books for Java EE developers - Learn Online, PDF download

Jakarta Struts is one of the most popular MVC frameworks to create a Java web application. Struts 1.0 had ruled the world in early 2000 era before Spring MVC took over. Still there are lots of projects written in Struts which needs active maintenance and that's why Struts developers are still in demand. It has not become anything like COBOL, but the latest version of Struts 2.0 is a capable web MVC framework with dependency injection and has a sizable community behind it. It has close competition with Spring MVC but given the demand for Struts developer, it's still a good technology to learn if you are looking for the job in Java web development position. What is the best way to learn Struts? Well, you can start with books and who doesn't like free eBooks and I am going to share some of the good free Ebooks to learn Struts, useful for both Java and J2EE developers.

Top 30 OOPS Concept Interview Questions Answers in Java

Java is an object-oriented programming language and you will see a lot of object oriented programming concept questions on Java interviews. The classic questions like difference between interface and abstract class are always there but from the last couple of years more sophisticated questions based upon advanced design principles and patterns are also asked to check OOP knowledge of the candidate. Though, Object oriented programming questions are more popular on Java interviews for 1 to 3 years experienced programmers. It makes sense as well, as these are the programmers who must know the OOP basic like Abstraction, Inheritance, Composition, Class, Object, Interface, Encapsulation etc. If you look for Java interview questions for 2 to 4 years experienced programmer, you will find lots of questions based upon OOP fundamentals like Inheritance and Encapsulation but as you gain more experience, you will see questions based upon object oriented analysis and design e.g. code a vending design machine or implement a coffeemaker in Java. These questions are more difficult and require not only true understanding of OOP fundamental but also about SOLID design principles and patterns.

Difference between Primary and Foreign key in table - SQL

The database is a collection of tables and a table is the collection of rows or records. A primary key is the data to uniquely identify a row in the table. For example, if an Employee table has millions of rows and emp_id is a primary key then it can uniquely identify that row. You can use this primary key to retrieve (SELECT) the row, update the row and delete the row. In SQL, a table can have only one primary key but it can contain more than one columns. There are two types of primary key, a simple primary key, and a composite primary key. A simple primary key is made of just one column while a composite primary key is made of more than one columns. Primary key also enforces some constraint e.g. UNIQUE and NOT NULL, which means if you try to enter another record with the primary key already existing in the database than DBMS will reject it. Similarly, a primary key cannot be NULL, it must have some value. On the other hand, the foreign key is just the primary key of another table. In a relational database, two tables can be related to each other e.g. Employee and Department, those cases, the primary key of one table becomes the foreign key of another table. In this article, you will learn some key difference between the Primary and foreign key in a table. This is also one of the most common SQL Interview questions for 1 to 2 years experience programmers.

6 Good Websites to Learn JavaScript Online - Best of Lot

We live in the world of internet which is full of resource. You can learn whatever you want and that too without spending too much of money. If you want to learn JavaScript there are plenty of websites where you can learn JavaScript online for FREE. You don't need to pay any fees, but you must have a good internet connection to take full advantage of these online resources. Out of so many websites which offer free tutorials, articles, blog post, videos, and podcasts, I have chosen these six websites to recommend to anybody who wants to learn JavaScript. I am a Java developer, but I have learned JavaScript by following this tutorial, Why? because I usually have to work on Java based web application which uses Servlet and JSP for server side scripting, but we always use JavaScript and jQuery for client side scripting.

Java Interview Questions Answers for Freshers (1 to 4 years experienced)

I have shared many posts about Java Interview Questions but in this article, I will share Java Interview questions and answers especially for junior Java developers. This includes college graduates, who are looking for the job, Java programmers who have 1 to 2 years of experience in Java and junior developers who have 2 to 4 years of experience in Java, C++ etc. At this level, Java questions are usually not very tough. If you have good knowledge of key programming areas e.g. data structure and algorithms, and a good understanding of Java programming language and JDK API, then you are in good shape. Interviewer often looks for candidates who are willing to learn, good at learning in quick time and knows basic stuff e.g. sorting list, searching through the array, starting stopping a thread and can read existing code. In this article, you will find questions from the areas targeted by Interview for freshers and Java developers with 1 to 4 years of experience e.g. coding, arrayOOP, main methodCollections, ArrayListEnums, Threads, design patterns, JDBC, SQL, Linux and other basic concepts.

How to set JAVA_HOME (PATH) in Mac OS X 10.10 Yosemite

You can set JAVA_HOME in Mac OS X 10,10 or Yosemite by adding following command in your ~/.bash_profile file, as shown below:

export JAVA_HOME=`/usr/libexec/java_home` (remember backticks)
or
echo export "JAVA_HOME=\$(/usr/libexec/java_home -v 1.7)" >> ~/.bash_profile

This will append export "JAVA_HOME=\$(/usr/libexec/java_home -v 1.7)" into your bash_profile file. If you have set JAVA_HOME in UNIX then it's exactly similar to that.

Top 10 Android Interview Questions Answers for Java Programmers

How many interview question do you prepare before going for any Android or Java interview? not many right. In this article, we will explore some of the most frequently asked Android interview questions. Android is very hot nowadays as its one of the top operating system for Mobile and Smartphone and the close rival to Apple's iOS. Android application developer job is in demand as well. I have also seen a couple of Java questions in Android interview as well. It means it's better to prepare some Java questions as well. Following Android Interview Questions are very basic in nature but appear frequently on beginners or Intermediate programmer level on various Android interview. I have not provided answers of this question as it can easily be found by doing the google. If needed I will update this Android interview questions with answers as well. These questions are good for recap and practice before going to Android interview.

10 Frequently asked SQL Query Interview Questions

In this article, I am giving some examples of SQL queries which is frequently asked when you go for a programming interview, having one or two year experience on this field. Whether you go for Java developer position, QA, BA, supports professional, project manager or any other technical position, may interviewer expect you to answer basic questions from Database and SQL. It's also obvious that if you are working from one or two years on any project there is good chance that you come across to handle database, writing SQL queries to insert, update, delete and select records. One simple but effective way to check candidate's SQL skill is by asking these types of simple query. They are are neither very complex nor very big, but yet they cover all key concept a programmer should know about SQL.

3 Key difference between multi-threading and multitasking?

In the programming world, there are two main ways to improve the throughput of a program,  by using multi-threading and by using multitasking. Both take advantage of parallelism to efficiently utilize immense power of CPU and improve the throughput of your program. Actually, multi-threading is nothing but a thread based multi-tasking. Since the difference between multi-threading and multi-tasking is an important freshers programming interview question and also often ask in viva or oral exams on computer science graduation courses, I thought to jot down a couple of important points together. This article is the result of those points and can be handy when you quickly wants to know the key difference between multi-threading and multi-tasking in concurrent programming.

2 Ways to find duplicate elements in an Array - Java

Problem: You have given an array of objects, which could be an array of integers and or array of Strings or any object which implements the Comparable interface. How would you find duplicate elements from an array? Can you solve this problem in O(n) complexity? This is actually one of the frequently asked coding problems from Java interviews. There are multiple ways to solve this problem and you will learn two popular ways here, first the brute force way, which involves comparing each element with every other element and other which uses a hash table like data structure to reduce the time complexity of problem from quadratic to linear, of course by trading off some space complexity. This also shows that how by using a suitable data structure you can come up with a better algorithm to solve a problem. If you are preparing for programming job interviews, then I also suggest you take a look at Cracking the Coding Interview book, which contains 150 programming questions and solutions, good enough to do well on any programming job interviews e.g. Java, C++, Python or Ruby.

How to Sort List into Ascending and Descending Order in Java

ArrayList, Set Sorting in Ascending – Descending Order Java
Sorting List, Set and ArrayList in Java on ascending and descending order is very easy, You just need to know correct API method to do that. Collections.sort()  method will sort the collection passed to it,  doesn't return anything just sort the collection itself.  Sort() method of Collections class in Java is overloaded where another version takes a Comparator and sort all the elements of Collection on order defined by Comparator.If we  don't pass any Comparator than object will be sorted based upon there natural order like String will be sorted alphabetically or lexicographically. Integer will be sorted numerically etc. Default sorting order for an object is ascending order like Integer will be sorted  from low to high while descending order is just opposite. Collections.reverseOrder() returns a Comparator which will be used for sorting Object in descending order.

Top 10 Tricky Java interview questions and Answers

What is a tricky question? Well, tricky Java interview questions are those questions which have some surprise element on it. If you try to answer a tricky question with common sense, you will most likely fail because they require some specific knowledge. Most of the tricky Java questions comes from confusing concepts like function overloading and overriding, Multi-threading which is really tricky to master, character encoding, checked vs unchecked exceptions and subtle Java programming details like Integer overflow. Most important thing to answer a tricky Java question is attitude and analytical thinking, which helps even if you don't know the answer. Anyway in this Java article we will see 10 Java questions which are real tricky and requires more than average knowledge of Java programming language to answer them correctly. As per my experience, there is always one or two tricky or tough Java interview question on any core Java or J2EE interviews, so it's good to prepare tricky questions from Java in advance.

If I take an interview, I purposefully put this kind of question to gauge the depth of candidate's understanding in Java. Another advantage of asking such question is the surprising element, which is a key factor to put the candidate on some pressure during interviews.

Since these questions are less common, there is good chance that many Java developer doesn't know about it.  You won't find these questions even on popular Java interview books like Java Programming Interview exposed, which is nevertheless an excellent guide for Java interviews.

Btw, if you don't find these question tricky enough, then you should check Joshua Bloch's another classic book, Java Puzzlers for super tricky questions. I am sure you will find them challenging enough.




10 Tricky Java interview question - Answered

Here is my list of 10 tricky Java interview questions, Though I have prepared and shared lot of difficult core Java interview question and answers, But I have chosen them as Top 10 tricky questions because you can not guess answers of this tricky Java questions easily, you need some subtle details of Java programming language to answer these questions.

Question: What does the following Java program print?
public class Test {
    public static void main(String[] args) {
        System.out.println(Math.min(Double.MIN_VALUE, 0.0d));
    }
}
Answer: This question is tricky because unlike the Integer, where MIN_VALUE is negative, both the MAX_VALUE and MIN_VALUE of the Double class are positive numbers. The Double.MIN_VALUE is 2^(-1074), a double constant whose magnitude is the least among all double values. So unlike the obvious answer, this program will print 0.0 because Double.MIN_VALUE is greater than 0. I have asked this question to Java developer having experience up to 3 to 5 years and surprisingly almost 70% candidate got it wrong.




What will happen if you put return statement or System.exit () on try or catch block? Will finally block execute?
This is a very popular tricky Java question and it's tricky because many programmers think that no matter what, but the finally block will always execute. This question challenge that concept by putting a return statement in the try or catch block or calling System.exit() from try or catch block. Answer of this tricky question in Java is that finally block will execute even if you put a return statement in the try block or catch block but finally block won't run if you call System.exit() from try or catch block.


Question: Can you override a private or static method in Java?
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java. Anyway, you can not override a private or static method in Java, if you create a similar method with same return type and same method arguments in child class then it will hide the superclass method, this is known as method hiding.

Similarly, you cannot override a private method in sub class because it's not accessible there, what you do is create another private method with the same name in the child class. See Can you override a private method in Java or more details.



Question: What do the expression 1.0 / 0.0 will return? will it throw Exception? any compile time error?
Answer: This is another tricky question from Double class. Though Java developer knows about the double primitive type and Double class, while doing floating point arithmetic they don't pay enough attention to Double.INFINITY, NaN, and -0.0 and other rules that govern the arithmetic calculations involving them. The simple answer to this question is that it will not throw ArithmeticExcpetion and return Double.INFINITY.

Also, note that the comparison x == Double.NaN always evaluates to false, even if x itself is a NaN. To test if x is a NaN, one should use the method call Double.isNaN(x) to check if given number is NaN or not. If you know SQL, this is very close to NULL there.

Btw, If you are running out of time for your interview preparation, you can also check out Java Programming Interviews exposed for more of such popular questions,

tricky core Java interview questions and answers



Does Java support multiple inheritances?
This is the trickiest question in Java if C++ can support direct multiple inheritances than why not Java is the argument Interviewer often give. Answer of this question is much more subtle then it looks like, because Java does support multiple inheritances of Type by allowing an interface to extend other interfaces, what Java doesn't support is multiple inheritances of implementation. This distinction also gets blur because of default method of Java 8, which now provides Java, multiple inheritances of behavior as well. See why multiple inheritances are not supported in Java to answer this tricky Java question.



What will happen if we put a key object in a HashMap which is already there?
This tricky Java question is part of another frequently asked question, How HashMap works in Java. HashMap is also a popular topic to create confusing and tricky question in Java. Answer of this question is if you put the same key again then it will replace the old mapping because HashMap doesn't allow duplicate keys. The Same key will result in the same hashcode and will end up at the same position in the bucket.

 Each bucket contains a linked list of Map.Entry object, which contains both Key and Value. Now Java will take the Key object from each entry and compare with this new key using equals() method, if that return true then value object in that entry will be replaced by new value. See How HashMap works in Java for more tricky Java questions from HashMap.



Question: What does the following Java program print?
public class Test {
    public static void main(String[] args) throws Exception {
        char[] chars = new char[] {'\u0097'};
        String str = new String(chars);
        byte[] bytes = str.getBytes();
        System.out.println(Arrays.toString(bytes));
    }
}

Answer: The trickiness of this question lies on character encoding and how String to byte array conversion works. In this program, we are first creating a String from a character array, which just has one character '\u0097', after that we are getting the byte array from that String and printing that byte. Since \u0097 is within the 8-bit range of byte primitive type, it is reasonable to guess that the str.getBytes() call will return a byte array that contains one element with a value of -105 ((byte) 0x97).

However, that's not what the program prints and that's why this question is tricky. As a matter of fact, the output of the program is operating system and locale dependent. On a Windows XP with the US locale, the above program prints [63], if you run this program on Linux or Solaris, you will get different values.

To answer this question correctly, you need to know about how Unicode characters are represented in Java char values and in Java strings, and what role character encoding plays in String.getBytes().

In simple word, to convert a string to a byte array, Java iterate through all the characters that the string represents and turn each one into a number of bytes and finally put the bytes together. The rule that maps each Unicode character into a byte array is called a character encoding. So It's possible that if same character encoding is not used during both encoding and decoding then retrieved value may not be correct. When we call str.getBytes() without specifying a character encoding scheme, the JVM uses the default character encoding of the platform to do the job.

The default encoding scheme is operating system and locale dependent. On Linux, it is UTF-8 and on Windows with a US locale, the default encoding is Cp1252. This explains the output we get from running this program on Windows machines with a US locale. No matter which character encoding scheme is used, Java will always translate Unicode characters not recognized by the encoding to 63, which represents the character U+003F (the question mark, ?) in all encodings.



If a method throws NullPointerException in the superclass, can we override it with a method which throws RuntimeException?
One more tricky Java questions from the overloading and overriding concept. The answer is you can very well throw superclass of RuntimeException in overridden method, but you can not do same if its checked Exception. See Rules of method overriding in Java for more details.



What is the issue with following implementation of compareTo() method in Java
public int compareTo(Object o){
   Employee emp = (Employee) o;
   return this.id - e.id;
}
where an id is an integer number.
Well, three is nothing wrong in this Java question until you guarantee that id is always positive. This Java question becomes tricky when you can't guarantee that id is positive or negative. the tricky part is, If id becomes negative than subtraction may overflow and produce an incorrect result. See How to override compareTo method in Java for the complete answer of this Java tricky question for an experienced programmer.



How do you ensure that N thread can access N resources without deadlock?
If you are not well versed in writing multi-threading code then this is a real tricky question for you. This Java question can be tricky even for the experienced and senior programmer, who are not really exposed to deadlock and race conditions. The key point here is ordering, if you acquire resources in a particular order and release resources in the reverse order you can prevent deadlock. See how to avoid deadlock in Java for a sample code example.



Question: Consider the following Java code snippet, which is initializing two variables and both are not volatile, and two threads T1 and T2 are modifying these values as following, both are not synchronized
int x = 0;
boolean bExit = false;

Thread 1 (not synchronized)
x = 1; 
bExit = true;

Thread 2 (not synchronized)
if (bExit == true) 
System.out.println("x=" + x);
Now tell us, is it possible for Thread 2 to print “x=0”?

Answer: It's impossible for a list of tricky Java questions to not contain anything from multi-threading. This is the simplest one I can get. Answer of this question is Yes, It's possible that thread T2 may print x=0.Why? because without any instruction to compiler e.g. synchronized or volatile, bExit=true might come before x=1 in compiler reordering. Also, x=1 might not become visible in Thread 2, so Thread 2 will load x=0. Now, how do you fix it?

 When I asked this question to a couple of programmers they answer differently, one suggests to make both threads synchronized on a common mutex, another one said make both variable volatile. Both are correct, as it will prevent reordering and guarantee visibility.

But the best answer is you just need to make bExit as volatile, then Thread 2 can only print “x=1”. x does not need to be volatile because x cannot be reordered to come after bExit=true when bExit is volatile.


What is difference between CyclicBarrier and CountDownLatch in Java
Relatively newer Java tricky question, only been introduced from Java 5. The main difference between both of them is that you can reuse CyclicBarrier even if Barrier is broken, but you can not reuse CountDownLatch in Java. See CyclicBarrier vs CountDownLatch in Java for more differences.


What is the difference between StringBuffer and StringBuilder in Java?
Classic Java questions which some people think tricky and some consider very easy. StringBuilder in Java was introduced in JDK 1.5 and the only difference between both of them is that StringBuffer methods e.g. length(), capacity() or append() are synchronized while corresponding methods in StringBuilder are not synchronized.

Because of this fundamental difference, concatenation of String using StringBuilder is faster than StringBuffer. Actually, it's considered the bad practice to use StringBuffer anymore, because, in almost 99% scenario, you perform string concatenation on the same thread. See StringBuilder vs StringBuffer for more differences.



Can you access a non-static variable in the static context?
Another tricky Java question from Java fundamentals. No, you can not access a non-static variable from the static context in Java. If you try, it will give compile time error. This is actually a common problem beginner in Java face when they try to access instance variable inside the main method. Because main is static in Java, and instance variables are non-static, you can not access instance variable inside main. See, why you can not access a non-static variable from static method to learn more about this tricky Java questions.


How many String objects are created by the following code?
Tricky Core Java questions with answers


Now, it's practice time, here are some questions for you guys to answer, these are contributed by readers of this blog, big thanks to them.
  1. When doesn't Singleton remain Singleton in Java?
  2. is it possible to load a class by two ClassLoader?
  3. is it possible for equals() to return false, even if contents of two Objects are same?
  4. Why compareTo() should be consistent to equals() method in Java?
  5. When do Double and BigDecimal give different answers for equals() and compareTo() == 0. 
  6. How does "has before" apply to volatile work?
  7. Why is 0.1 * 3 != 0.3,
  8. Why is (Integer) 1 == (Integer) 1 but (Integer) 222 != (Integer) 222 and which command arguments change this.
  9. What happens when an exception is thrown by a Thread?
  10. Difference between notify() and notifyAll() call?
  11. Difference between System.exit() and System.halt() method?
  12. Does following code legal in Java? is it an example of method overloading or overriding?
  13. public String getDescription(Object obj){
       return obj.toString;
    }
    public String getDescription(String obj){
       return obj;
    }
    and
    public void getDescription(String obj){
       return obj;
    }


This was my list of Some of the most common tricky questions in Java. It's not a bad idea to prepare tricky Java question before appearing for any core Java or J2EE interview. One or two open-ended or tricky question is quite common in Java interviews.


Further Reading
If you are looking for super challenging trick coding questions then you should check out Joshua Bloch another classic book, the Java Puzzlers, I am sure you ill find them really challenging to solve, I certainly did.

tricky core Java interview questions



Hungry for more Java Interview Question and Answer post, check out these articles

How to Print Pyramid Pattern in Java? Program Example

Pattern based exercises are a good way to learn nested loops in Java. There are many pattern based exercises and one of them is printing Pyramid structure as shown below:


* * 
* * * 
* * * * 
* * * * * 

You need to write a Java program to print above pyramid pattern. How many levels the pyramid triangle would have will be decided by the user input. You can print this kind of pattern by using print() and println() method from System.out object. System.out.print() just prints the String or character you passed to it, without adding a new line, useful to print stars in the same line. While, System.out.println() print characters followed by a newline character, which is useful to move to next line. You can also use Scanner class to get input from the user and draw pyramid up to that level only. For example in above diagram, the pyramid has 5 levels.

Java ArrayList Tutorial - The MEGA List

I have written several ArrayList tutorials, touching different ArrayList concepts and many how to do examples with ArrayList. In this tutorial, I am giving a summary of each of them. Why? So that any Java beginner who wants to learn ArrayList in detail, can go through the relevant tutorial and learn. It's also on request of many of my readers, who asked in past to share all the relevant tutorials in one place. Why should you learn ArrayList? Because it's the most important Collection class in Java. You will often find yourself using ArrayList and HashMap in tandem. It's your dynamic array which can resize itself as it grows. In another word, ArrayList is as much important as an array. When I started learning Java, my quest to ArrayList starts as a dynamic array, because there were many scenarios where we don't know the size of the array in advance. We end up either allocating less space or more space, both are not ideal. Btw, you should also check out Head First Java 2nd Edition if you are newbie and Effective Java 2nd Edition, if you know Java but wants to become a Java expert.

How to solve FizzBuzz in Java?

FizzBuzz is one of the most frequently asked questions on programming interviews and used to filter programmers who can't program. It looks extremely simple but it's tricky for those programmers or coder who struggle to structure their code. Fizzbuzz problem statement is very simple, write a program which return "fizz" if the number is a multiplier of 3, return "buzz" if its multiplier of 5 and return "fizzbuzz" if the number is divisible by both 3 and 5. If the number is not divisible by either 3 or 5 then it should just return the number itself. You can see nothing is fancy when it comes to thinking about the solution, but when you start coding, you will see a problem with structuring your code, particularly if else blocks.

How to convert float to int in Java? Examples

Even though both float and int are 32-bit wide data type, float has the higher range than integer primitive value. Since a float is a bigger than int, you can convert a float to an int by simply down-casting it e.g. (int) 4.0f will give you integer 4. By the way, you must remember that type casting just get rid of anything after the decimal point, they don't perform any rounding or flooring operation on the value. So if your float value is 3.999, down casting to an integer will produce 3, not 4. If you need rounding then consider using Math.round() method, which converts float to its nearest integer by adding +0.5 and then truncating it. Math.random() is overloaded for both float and double, so you can use this for converting double to long as well. Let's see an example of converting a float value to int in Java.

Top 5 FREE JavaScript Books - Download PDF or Read Online

The internet is full of good things and one of them is free eBooks and PDF. Programmers can almost run anything by these free books. Earlier I have shared some of the freely available Java Programming books and PDF and in this article, I am going to share 5 good books to learn JavaScript which are free to read online or allow you to download PDF for offline reading. JavaScript is probably another language I recommend someone who knows Java, Why? because it's really ubiquitous. There is almost no website which is not using JavaScript in one or other format. Some use JavaScript for client-side scripting and animation, while other use JavaScript on the server side with libraries like node.js, it forms the unique triangle with HTML and CSS.

How to declare ArrayList with values in Java? Examples

Sometimes you want to create an ArrayList with values, just like you initialize t at the time of declaration, as shown below:

int[] primes = {2, 3, 5, 7, 11, 13, 17};
or
String[] names = {"john", "Johnny", "Tom", "Harry"};

but unfortunately, ArrayList doesn't support such kind of declaration in Java. But don't worry, there is a workaround  to declare an ArrayList with values e.g. String, integers, floats or doubles by using Arrays.asList() method, which is nothing but a shortcut to convert an Array to ArrayList.

Java - How to convert from Integer to String?

This is the second part of data conversion tutorial, in the first part you have learned how to convert String to Integer and in this article, you will learn the opposite i.e. convert from Integer to String. Actually, you can apply all the tricks, which I had told you before about converting long to String, and autoboxing will take care of converting int to Integer in Java. But, if you care for performance and believe in not using auto-boxing when not needed then there are still a couple of ways which directly converts an Integer object to String e.g. Integer.toString() method, which returns a String object and doesn't have any auto-boxing overhead. Let's see a couple of more ways to convert an Integer to String in Java. Btw, if you are new to Java and just started learning, I suggest you to buy the Head First Java, 2nd Edition, one of the best books to learn Java.

Error: could not open 'C:\Java\jre8\lib\amd64\jvm.cfg'

A couple of weeks back I updated my laptop to Windows 10 but after trying for one day, I reverted back to Windows 8.1. Everything was alright until I open Eclipse, which was throwing "Error: could not open 'C:\Program Files\Java\jre8\lib\amd64\jvm.cfg', as soon as I launch it. It was quite bizarre because everything was fine earlier. I suspect Java installation problem, so I went to command prompt and typed Java, only to find the same error there as well. You can see below, I am just trying to run the "java" command from MS-DOS window. Here "java" command is picked from PATH environment variable.

Avoid ConcurrentModificationException while looping over Java ArrayList?

Apart from the NullPointerException and ClassNotFoundException, ConcurrentModificationException is another nightmare for Java developers. What makes this error tricky is the word concurrent, which always mislead Java programmers that this exception is coming because multiple threads are trying to modify the collection at the same time. Then begins the hunting, they spent countless hours to find the code which has the probability of concurrent modification. While in reality ConcurrentModficationException can also come on the single threaded environment. To give you an example, just loop over a list using for loop and try to remove one element, you will get the ConcurrentModificatoinExcetpion? Why? because you broke the rule of not modifying a Collection during iteration.

How to find highest repeating word from a text File in Java - Word Count Problem

How to find the word and their count from a text file is another frequently asked coding question from Java interviews. The logic to solve this problem is similar to what we have seen in how to find duplicate words in a String. In the first step you need to build a word Map by reading contents of a text File. This Map should contain word as a key and their count as value. Once you have this Map ready, you can simply sort the Map based upon values. If you don't know how to sort a Map on values, see this tutorial first. It will teach you by sorting HashMap on values. Now getting key and value in sorted should be easy, but remember HashMap doesn't maintain order, so you need to use a List to keep the entry in sorted order. Once you got this list, you can simply loop over the list and print each key and value from the entry. This way, you can also create a table of words and their count in decreasing order.  This problem is sometimes also asked as to print all word and their count in tabular format.

Thread-safe Singleton in Java using Double Checked Locking Idiom

Singleton Pattern is one of the famous design patterns from the Gang of Four. Even though nowadays it is considered as an anti-pattern, it has served us well in the past. In Singleton pattern, a class has just one instance throughout its lifetime and that instance is shared between multiple clients. Singleton class has two responsibility, first to ensure that only instance of the class gets created and second, provide a method getInstance() so that everyone can get access to that single instance i.e. global access. One of the issue, faced by Singelton design pattern in the multi-threading program is to ensure that just one instance of the class gets created, even if multiple clients called getInstance() method same time. Many programmers solved this problem by making whole getInstance() method synchronized, which results in poor performance because every time a thread enters a synchronization method, it acquires the lock and while it's been inside the method, no other thread are allowed to enter, even if they are not creating instance and just accessing already created instance.

How to check if a key exists in HashMap Java? Use containsKey()

One of the common programming task while using HashMap in Java is to check if a given key exists in the map or not. This is supposed to be easy, right? Yes, it is easy if you know your API well, all you need to is call the containsKey() method, it returns true if given key exists in HashMap, otherwise false; but I have seen many programmer's codes like we will see in this article, which prompted me to write this blog post.

if(map.get(key) !=  null){
    System.out.println("key exits in Map");
}

This code is fragile, it will not work if you have added null values into HashMap, remember HashMap does allow null values. Many programers will test this code for some input and think that it's working fine, only to create a subtle bug in production.  It's always better to use an API method if it can do the job, many greats have advised this. Joshua Bloch even included a chapter on his classic book Effective Java, a must-read book for any Java programmer.

6 ways to convert char to String in Java - Examples

If you have a char value e.g. 'a' and you want to convert it into equivalent String e.g. "a" then you can use any of the following 6 methods to convert a primitive char value into String in Java :

1) String concatenation
2) String.valueOf()
3) Character.toString()
4) Character wrapper class + toString
5) String constructor with char array
6) String.valueOf(char [])

In this article, we will see examples of each approach and learn a little bit more about it. Actually, there is lot of overlap between each method as some of them internally calls String.valueOf(), which eventually calls to a String constructor which accepts char array and creates a String object containing primitive char value with length 1. Once you know, how they work internally, it easy to decide which one is more efficient for purpose.

60+ Java Interview Questions for Quick Revision

Java Interviews are very different than traditional software developer interviews. You can clear a Java interview without even writing a single line of code, Yes, this is true, you can become a Java developer without someone asking you to write a function in Java interview. Though, it's not the case everywhere and many companies are increasingly including coding test in their Java developer interview process, but there are many companies and start-ups where you can get a Java job without writing a single line of code. All you need to do is memorize those standard Java questions, which has been asked from ages and mostly test the theoretical knowledge of the candidate. This is great for candidates which lack hands-on coding experience, but sometimes this style of the interview can cost you good developers who are not good at interviews. Someone, who knows how to structure a complex program, knows how to model their class and objects, can write good, robust code but fail to answer questions like, Why String is Immutable? or How HashMap works in Java?

How to use BigInteger class in Java? Large Factorial Example

When you calculate factorial of a relatively higher number most of the data type in Java goes out of their limit. For example, you cannot use int or long variable to store factorial of a number greater than 50. In those scenarios where int and long are not big enough to represent an integral value, you can use java.math.BigInteger class. BigInteger variable can represent any integral number, there is no theoretical limit, but it allocates only enough memory required to hold all the bits of data it is asked to hold. There is not many time you need this class but its good to know about it and that's why I am giving one scenario which is perfectly suitable for using BigInteger class. In this article, you will learn how to calculate factorial of large number using BigInteger object. We will use same formula, we have used to calculate normal factorials as discussed in my previous post about factorials.

Top 10 Algorithm books Every Programmer Should Read

Algorithms are language agnostic and any programmer worth their salt should be able to convert them to their language of choice. Unfortunately, I have come across several programmers who are REALLY good on programming language e.g. Java, knows minor details of API and language intricacies but has very poor knowledge of algorithms. Ask them to right popular sorting algorithms e.g. quicksort and they will fall apart. Expecting them to know of about more complex algorithm e.g. String, graph, tree or greedy algorithms. Once, I have asked a very good candidate who was good in Java, multi-threading but his data structure and algorithm skill was really poor to his experience and caliber.  I asked him, why he didn't spent time brushing his algorithm and problem solving skill before coming to interview? His excuse was "those algorithms are just for interviews and never really used in practical coding. I have never used them in my 6 years of Java development career". He was right, but he failed to recognize the more long term improvement algorithm and data structure do in improving programming skill. They are tool of developing programming solving skill and coding sense, which is required to convert a user requirement into line of code also known as computer program.

How to sort HashSet in Java? Example

Somebody asked me recently, how do you sort an HashSet? For lists, we use the Collections.sort(List) method, but there is nothing for Set. If I have an HashSet then how would I go about sorting it? The answer is you cannot sort an HashSet, why? because HashSet is an unordered collection. When you insert an element in HashSet than you lose the order guarantee. You cannot do reordering or sorting in Set because it does not have random access methods (ie, .get() an element at a given index), which is basically required for sort algorithms. Though you can sort the HashSet by first converting HashSet to List and then sorting it. Also, some of Set implementation may keep the order intact e.g. LinkedHashSet maintains insertion order, which means you can sort LinkedHashSet but not HashSet. Alternatively, you can also use TreeSet to keep elements in the sorted order from the start.

Factorial in Java using Recursion and Loop

Problem : Write a program to calculate factorial of a given number in Java, using both recursion and iteration.

Solution : If you come from Maths background then you know that factorial of a number is number*(factorial of number -1). You will use this formula to calculate factorial in this  Java tutorial. Since factorial is a naturally recursive operation, it make sense to use recursion to solve this problem but its not always the best way. Iteration provides a more robust way, but don't worry you will learn how to calculate factorial with and without recursion in Java. By the way, factorial of numbers grows very quickly and even the largest integral data type in Java, long is not able to hold factorial of anything or above 50. In such cases you can use BigInteger, which has theoretically no limit and can be used to represent very large integral numbers.

Why you shouldn't use == with float and double in Java?

In this article, you are going to learn why you shouldn't use == with float and double in Java? Especially for checking loop termination condition. Java programmers often make the mistake of using floating point number in a loop and checking condition with the == operator, in the worst case this could create an infinite loop, causing your Java application to hung.


For example, following code will not work as you expect :

for(double balance = 10; balance!=0; balance-=0.1) {
   System.out.println(balance);
}

Top 10 RESTful Web Service Interview Questions for Java Developers

REST is an architectural style of developing web services which has become immensely popular in last couple of years and consequently gained lot of importance in core Java and Java EE interviews. If you are a Java web developer then you are most likely see couple of questions from web services every time you go for a Java web developer interview. One of the most frequently one is difference between REST and SOAP web services, which I have recently answered there, but there are lot many other good questions I have collected from friends and my readers, which I have not yet published. In this article, I am sharing those questions, mainly based upon REST style web services for your practice and preparation. Some of them are easy to answer and you will find them either in my blog or by doing Google but couple of them is really interesting and challenging and required real solid experience in Java web service domain to answer. I leave it to you guys for now and will probably update this post with answers in near future. If you don't find answer of any REST interview question then I suggest you to take a look at these two books, Java Programming Interview Exposed and RESTful Web Services, you will most likely find your answer there.

How to convert list to array in Java and vice-versa

There is no easy way to convert an array to list in Java, but you can easily convert a list into array by calling toArray() method, which List inherit from Collection interface. If you solely rely on core JDK, then only way to convert an array to list is looping over array and populating list one element at a time. But if you can use open source libraries like Google Guava or Apache Commons lang then there is many utility classes to convert list to array and vice-versa, as shown in this tutorial. If you are working on Java application, you will often need to convert between list and array. A list is nothing but a dynamic array which knows how to re-size itself when it gets full or get close to full. List uses load factor to decide when to re-size, default value of its is 0.75. When they re-size, list usually double their slots e.g. goes from 16 to 32 etc. You can find these nifty details in their implementation classes e.g. ArrayList is one of the popular list in Java which provides order and random access. BTW, if you want to truly master Java Collection framework, then you must read Java Generics and Collection book, written by Maurice Naftaline and one of the must read book to become expert on Java Collections framework.

How to randomize elements in List in Java using shuffle method

java.util.Collections class provides shuffle() method which can be used to randomize object stored in a List in Java. Since List is an ordered collection and maintains the order on which objects are inserted into it, you may need to randomize elements if you need them in a different order. Collections.shuffle() method uses default randomness to randomize element but you also have an overloaded version of shuffle() to provide an instance of  java.util.Random object, which can be used to randomize elements. Since this method except a List, you can also pass it to LinkedList, VectorCopyOnWriteArrayList and others, which doesn't implement RandomAccess method. In such cases, this method convert list to array before shuffling to avoid quadratic performance by shuffling sequential access list. Once shuffling is done it also converts back array to list. Shuffling has many usage e.g. shuffling deck of cards in a poker game simulation. You can also use shuffling to roll dice if you are developing any board game which requires dice e.g. Ludo.

2 ways to parse String to int in Java

Java provides Integer.parseInt() method to parse a String to an int value, but that's not the only way to convert a numeric String to int in Java. There is, in fact, a better way, which takes advantage of the parsing logic of parseInt() method as well as caching offered by Flyweight design pattern, which makes it more efficient and useful. Yes, you guessed it right, I am talking about Integer.valueOf() method, which implements Flyweight design pattern and maintains a cached pool of frequently used int values e.g. from -128 to 127. So every time you pass a numeric String which is in the range of -128 to 127, Integer.valueOf() doesn't create a new Integer object but return the same value from cached pool. The only drawback is that Integer.valueOf() returns an Integer object and not an int primitive value like parseInt() method, but given auto-boxing is available in Java from JDK 5 onward, which automatically convert an Integer object to int value in Java.

Difference between Public, Private and Protected modifier in Java?

In Java, you have got something called access modifier, which specifies accessibility of class, methods and variables. There is four access modifier in Java namely public, private, protected and the default access modifier, also known as package level modifier. The difference between these access modifier comes in their ability to restrict access to a class, method or variables, public is the least restrictive access modifier while private is the most restrictive access modifier, package and protected lies in between. Another key difference between public, protected, package and private modifier come from the point where you can apply them, for example, you cannot use private or protected modifier with a top level class but you can use public modifier there.

How to reverse Integer in Java - LeetCode Solution

LeetCode has a problem to reverse digits of an integer number without using any library method like reverse() method of StringBuffer. In LeetCode, you can solve this problem with many different languages e.g. Java, C, C++, C#, Python, Ruby and even JavaScript. BTW, in the article, we will learn how to solve this problem in Java. Before approaching solution let's first read the problem statement :

Reverse digits of an integer.

Example 1: x = 123, return 321
Example 2: x = -123, return -321

The problem looks simple but it's not simple there are many things you need to consider in order to produce a solution which is accepted by LeetCode, which has thousands of test cases to test your solution.

19 Java Method Overloading and Overriding Interview Questions and Answers

Method overloading and overriding is one of the tricky concept to master and that's why its one of the most popular topic in Java Interviews. You will often see questions like what is difference between overloading and overriding? or can you overload method in same class? during first few rounds of interview, mostly at telephonic round. Since its part of object oriented fundamentals its also good to know as much about these concepts as possible. In this article, I am sharing some of the basic but frequently asked questions which are solely based upon overloading and overriding concept and their implementation in Java programming language. By going through these questions, You will not only do well on interviews but also it will improve your understanding of Java and OOP fundamentals. BTW, if you are seriously preparing for Java interviews, just preparing this topic will not be enough and you need to prepare other important topics as well e.g. Java Collection framework, multi-threading, JVM internals and garbage collections etc. If you are in hurry, I would suggest you to take a look at Java Programming Interview Exposed by Wrox publication, one of the better book on Java interviews.

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger in Java

Problem : You are getting Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger error in your Java application, which is using Log4j Logger either directly or indirectly via some popular Java framework like Spring, Struts or Hibernate.

How to swap two Integers without using temporary variable in Java?

One of the oldest trick question from programming interview is, How do you swap two integers without using temp variable? This was first asked to me on a C, C++ interview and then several times on various Java interviews. Beauty of this question lies both on trick to think about how you can swap two numbers with out third variable, but also problems associated with each approach. If a programmer can think about integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers. Ok, so let's come to the point, suppose you have tow integers i = 10 and j = 20, how will you swap them without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more or less in every other programming language, you need to do this using Java programming constructs. You can swap numbers by performing some mathematical operations e.g. addition and subtraction and multiplication and division, but they face problem of integer overflow.

How to load data from CSV file in Java - Example

You can load data from a CSV file in Java program by using BufferedReader class from java.io package. You can read the file line by line and convert each line into an object representing that data. Actually there are couple of ways to read or parse CSV file in Java e.g. you can use a third party library like Apache commons CSV or you can use Scanner class, but in this example we will use traditional way of loading CSV file using BufferedReader.

How to fix java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory

Problem : You are getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory in your Java program, which uses logging framework to log messages into log file.  It could be direct dependency or indirect dependency due to any framework e.g. Spring, Hibernate or any open source library like jackson or any other JSON parsing library.

HashSet vs TreeSet in Java? Similarities and Differences

HashSet and TreeSet both implement same interface i.e  java.util.Set interface and they possess the quality of Set interface means duplicate elements are not allowed. Both HashSet and TreeSet are used for to store unique elements, but HashSet doesn't care about any order and TreeSet keeps a thing in order. Ordering or sorting on TreeSet can be customized by using Comparator interface, by default TreeSet uses elements natural order for sorting, which is defined by compareTo() method of java.lang.Comparable interface. What is the difference between HashSet and TreeSet is is also one the frequently asked Java interview question, So you should know about similarities and difference between them? It also helps you to understand when to use both TreeSet and HashSet and what are the scenario when we should use this sets. Let's go through the similarities and difference between HashSet and TreeSet in Java.

How to join two threads in Java? Thread.join() example

You can join two threads in Java by using join() method from java.lang.Thread class. Why do you join threads? because you want one thread to wait for another before starts processing. It's like a relay race where the second runner waits until the first runner comes and hand over the flag to him. Remember, unlike sleep(), join() is not a static method so you need an object of java.lang.Thread class to call this method. Now, who calls and who wants and which thread dies? for example, if you have two threads in your program main thread and T1 which you have created. Now if your main thread executes this line T1.join() (main thread execute whatever you have written in the main method) then main thread will wait for T1 thread to finish its execution. The immediate effect of this call would be that main thread will stop processing immediately and will not start until T1 thread has finished. So, what will happen if T1 is not yet started and there is no one to start T1 thread? Well,  then you have a deadlock but if it's already finished then main thread will start again, provided it get the CPU back.

OCAJP 7 or OCAJP 8? Which Java Certification should I take?

Java certification is a great way to learn and master The Java programming language, do well on the interview and get recognition in the job, but the most common reason for doing Java certification is to find a job. After Oracle's acquisition and dividing old SCJP exam into two exams OCAJP and OCPJP, it has become really confusing for many developers to decide which Java certification exam they should take. Since technologies change fast and Java is no exception, it's just a year when Java 8 was released and now people are talking about Java 9. In general, it is better to go with the latest version of a certification, which is currently available i.e. the Java 8 version. But in the case of Java certifications, it's not that simple.

22 Array Concepts Interview Questions Answers in Java

The array is one of the fundamental data structure and most of other data structures are based upon it e.g. List, Hash tables are based upon arrays. Array based questions are quite popular on Java interviews. There are two types of question you will find, first which are based upon array implementation in Java and second which are based upon how to use array data structure to solve some problems. First type of question is quite popular in telephonic round of Java interview and second is usually asked on written test and face-to-face interviews. These questions are mostly collected from Java interviews for junior and intermediate programmers, who has 0 to 5 years of working experience in Java. Some tricky questions like question no 2 and 15 are also good for senior and more experienced Java professionals. In fact, one of my friend didn't got the question 15 right, he was actually surprised by the fact that you can make an array volatile in Java.

How to calculate Maximum and minimum in Java? Beginner Tutorial

Today's programming exercise for a beginner is to write a Java program to take input from the user and find out maximum and minimum number and print them into the console. The purpose of this article is to teach you how to get input from a user in Java and how to use java.lang.Math class to perform some mathematical operation e.g. max, min or average. You can use Scanner class, added in Java 1.5 to read user input from the console. Scanner needs an InputStream to read data and because you are reading from the console, you can pass System.in, which is InputStream for Eclipse console, or command prompt, depending upon what you are using. This class also helps you to convert user input into requiring data type e.g. if a user enters numbers then you must convert then into int data type and store them into int variable as shown in our example. You can use nextInt() method to read user input as Integer.