HTML

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 OOP Concept Interview Questions Answers in Java - Object Oriented Programming

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.

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 rights. 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 a various Android interview. I have not provided answers to 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.

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.

How to stop a thread in Java? Example

Today we're going to learn about how to stop a thread in Java. It's easy to start a thread in Java because you have a start() method but it's difficult to stop the thread because there is no working stop() method. Well, there was a stop() method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a boolean volatile variable.  If you remember, threads in Java start execution from run() method and stop, when it comes out of run() method, either normally or due to any exception. You can leverage this property to stop the thread. All you need to do is  create a boolean variable e.g. bExit or bStop. Your thread should check its value every iteration and comes out of the loop and subsequently from run() method if bExit is true. 

How to search an element inside LinkedList in Java? Example

You can search an element inside LinkedList in Java by using indexOf() and lastIndexOf() methods. Though LinkedList doesn't support random search like ArrayList, you can still go through the list, check each element and find out whether its interested element or not. Since java.util.LinkedList is an implementation of doubly linked list, these two methods are quite handy to search from either ends e.g. indexOf() method start search from head and return an element's position while lastIndexOf() starts the search from tail. Though the position is not relative to ends, they are always calculated from head. You can also use these two methods to find out duplicate elements. If an element is appeared twice in linked list then indexOf() and lastIndexOf() method will return different positions for that because it will be found at different position from head and tail. For unique elements, both these methods will return the same position.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver [Solution]

Problem : You are getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error while connecting to MySQL database from Java Program. You may be running your Java application directly from command prompt, shell script, ANT or Eclipse.

Cause : In order to connect to MySQL database, you need JDBC driver for MySQL. A class which implements java.sql.Driver interface for MySQL. Every vendor is responsible to implement this class for their databases. This driver implementation is provided by MySQL as MySQL java connector library. There is a class called com.mysql.jdbc.Driver which implements this interface.

'javac' is not recognized as an internal or external command

'javac' is not recognized as an internal or external command, operable program or batch file error comes when you try to compile a Java source file using javac command e.g. javac Helloworld.java but your PATH is not set properly. It means that javac.exe executable file, which exists in bin directory of JDK installation folder is not added to PATH environment variable. You need to add JAVA_HOME/bin folder in your machine's PATH to solve this error. You cannot compile and run Java program until your add Java into your system's PATH variable. Here is how this error looks like in command prompt of windows machine :

How to use Final keyword in Java? Examples

You can use the final keyword with variables, methods and classes in Java. You can use the final modifier with variables to make them constant. A final variable is initialized only once in its lifetime, once initialized you cannot change its value. Though you can initialize the final variable at the time you declare them or you can initialize them at constructor if they are blank final variable. A static final variable, also known as constant must be initialized in the same line. You can also use the final modifier with methods to prevent method overriding. In Java, you cannot override final methods. This is usually done to signal that method is complete and it's not designed for extension. It is also done to prevent someone deliberately or accidentally changing core logic of method by overriding it e.g. in template design pattern, the method which keeps the algorithm, also known as template method should be final because the outline of the algorithm should be changed by child classes.

How to parse String to long in Java? Example

You can parse a String literal containing valid long value into a long primitive type using parseLong() and valueOf() method of java.lang.Long class of JDK. Though there are couple of difference between valueOf() and parseLong() method e.g. valueOf() method return a Long object while parseLong() method return a Long object, but given we have autoboxing in Java, both method can used for parsing String to create long values. In the last article, you have learned how to convert a Long value to String in Java and in this tutorial, you will learn opposite, i.e. how to parse a String to a long value in Java. As I said, there are the couple of ways to do it, but the most important method is parseLong(). This method is responsible for parsing input String and creating primitive long value corresponding to input String. It does input validation and throws NumberFormatException if you pass String which is not valid long value e.g. alphanumeric String, String containing characters other than +, - and numbers, long values which are out of range, lonely + or - character etc.

How to convert long to String in Java? Example

There are three main ways to convert a long value to String in Java e.g. by using Long.toString(long value) method, by using String.valueOf(long) and by concatenating with an empty String. You can use any of these method to convert a long data type into String object. It's not very different than from how you convert an int to String in Java. Same method applies here as well. String concatenation seems the easiest way of converting a long variable to String, but others are also convenient.  If you look Java code for valueOf() method from java.lang.String class you will realize that it actually calls the toString() method of java.lang.Long class for conversion, which means there is only one method where logic of converting primitive long to String is written. Nevertheless, if you are not converting long in loop all method will perform same, but if you have to convert large number of long values to String then directly using Long.toString() method can be quite useful. 

How to add element at first and last position of linked list in Java?

LinkedList class in java.util package provides the addFirst() method to add an element at the start of the linked list (also known as head)  and addLast() method to add an element at the end of the linked list, also known as the tail of the linked list. Java's LinkedList class is an implementation of doubly linked list data structure but it also implements java.util.Deque interface and these two methods came from that interface, which means they are only available from Java 1.6 onward. addFirst() method insert the specified element at the beginning of the linked list and addLast() method insert the specified element at the end of the linked list.

What is difference between hard link and soft link in UNIX?

There are two types of links in UNIX system, hard link and soft links, also known as symbolic link or symlink. Though both points to some other source, there are a lot of difference between them. hard link is direct pointer to the inode of the original file. If you compare the original file with the hard link there won't be any differences between them. On other hand, a soft link is a file that have the information to point to another file or inode. That inode points to the data in the disk. Hard links are much more restrictive than soft links and that's why they are used rarely. Also not all file systems supports hard links but UNIX does. Earlier Windows file system doesn't support soft links but from Windows 2000 onward they are supporting it, both Windows Vista and Windows 7 support links now. MS DOS operating system doesn't support neither hard link nor soft link. You can use ln command in UNIX to create, update and remove soft links. I often use links for build and release management purpose e.g. our application never points to hard-coded file or directory instead it points to links which is updated on every release.

Difference between Type 1, 2, 3 and 4 JDBC Driver in Java?

One of the oldest Java interview question is what is the difference between different types of JDBC drivers e.g. what is the difference between type 1, type 2, type 3 or type 4 drivers? Sometimes also asked as how do you choose between different JDBC driver? When to use type 3 over type 4 driver etc. It's 2015 now and I doubt anyone is using JDBC driver other than type 4 for connecting to database, but let's see how to answer this question when you face it during the interview. The difference between different types of JDBC driver comes from the fact how they work, which is basically driven by two factors, portability, and performance. Type 1 JDBC driver is the poorest in terms of portability and performance while type 4 JDBC driver is highly portable and gives the best performance. You will learn more differences between different JDBC drivers as we go along.

How to use PriorityQueue in Java? An Example

PriorityQueue is another data structure from Java Collection framework, added in Java SE 5. This class implements Queue interface and provides a sorted element from the head of the queue. Though it provides sorting, it's little different with other Sorted collections e.g. TreeSet or TreeMap, which also allows you to iterate over all elements, in priority queue there is no guarantee on iteration. The only guaranteed PriorityQueue gives is that lowest or highest priority element will be on the head of the queue. So when you call remove() or poll() method, you will get this element and next on priority will acquire the head spot. Like other collection classes which provide sorting, PriorityQueue also uses Comparable and Comparator interface for priority.

5 Good Books to Learn Java 8 Functional Programming

TL;DR: I have read many books while learning Java 8, but the best book I found was Java SE 8 for Really Impatient from Cay S. Horstmann. Why I recommend this book? three reasons, first clarity, second, size of the book is not overwhelming, and the third and most important I was able to connect to this book. I didn't find it boring or feeling sleepy as soon as I started reading, which in my opinion is a litmus test for any book.  It's been more than a year since Java 8 was launched in March 2014 and number of Java developers looking to learn Java 8 features like lambda expression, streams, and new date and time API is increasing exponentially. Since Java 8 is  significantly different from earlier Java version, thanks to the functional programming approach introduced in this release to take advantage of multicore CPU, programmers are finding it hard to grasp new concepts.

How to append text to existing File in Java? Example

In the last tutorial, you have learned about how to write data to a file in Java and in this tutorial you will learn how to append text to a file in Java. What is the difference between simply writing to a file vs appending data to a file? In the case of writing to a file, a program can start writing from the start but in the case of appending text, you start writing from the end of the file. You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode. This means you can write new content at the end of the file. One of the common examples of appending text to file is logging but for that you don't need to write your own logger, there are several good logging library available in Java world e.g. Log4j, SLF4j, Logbak and even java.util.logging is good enough.

How to write to File in Java using BufferedWriter

You can use either OutputStream or Writer class in Java to write data to a file in Java. For example, you can use a combination of FileWriter and BufferedWriter to write text content into a text file in Java. If you want to write raw bytes consider using FileOutputStream class. Just remember that InputStream is used to read data and OutputStream is used to write data to file or socket. You can write anything to file e.g. String, integer, float values etc. Java provides DataOutputStream to write different data type directly into file e.g. writeInt() to write integer values, writeFloat() to write floating point values into file and writeUTF() to write String into File.  BufferedWriter, like its counterpart BufferedReader, allows you to perform buffered IO, which can drastically improve performance while reading large files.

java.lang.NoClassDefFoundError: org/dom4j/DocumentException [Solution]

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/DocumentException comes when your program is using DOM4j library but necessary JAR is not present. This error can also come when you are indirectly using DOM4j library e.g. when you use Apache POI library to read XLSX file in Java,  this library needs dom4j.jar in your classpath. Not just this one but there are several other libraries which use this JAR internally, if you are using any of them but don't have this JAR then your program will compile fine but fail at runtime because JVM will try to load this class but will not be able to find it on the classpath. Some curious developers might ask, why it didn't fail during compile time if JAR was not present there? Well, the reason for that is that your code might not be using any class file directly from the dom4j.jar file.

2 Ways to Read a Text File in Java 6

You can read a text file in Java 6 by using BufferedReader or Scanner class. Both classes provide convenient methods to read a text file line by line e.g. Scanner provides nextLine() method and BufferedReader provides readLine() method. If you are reading a binary file, you can use use FileInputStream. By the way, when you are reading text data, you also need to provide character encoding, if you don't then platform's default character encoding is used. In Java IO, streams like InputStream are used to read bytes and Readers like FileReader are used to read character data. BufferedReader is the traditional way to read data because it reads file buffer by buffer instead of character by character, so it's more efficient if you are reading large files. BufferedReader is also there from JDK 1 itself while Scanner was added to Java 5.

How to Check is a String is Palindrome in Java using Recursion

In this tutorial, you will learn how to check if a string is a palindrome in Java using recursion. A String is nothing but a collection of characters e.g. "Java" and String literals are encoded in double quotes in Java. A String is said to be a palindrome if the reverse of String is equal to itself e.g. "aba" is a palindrome because the reverse of "aba" is also "aba", but "abc" is not a palindrome because the reverse of "abc" is "cba" which is not equal. Recursion means solving a problem by writing a function which calls itself. In order to check if String is a palindrome in Java, we need a function which can reverse the String. Once you have original and reversed String, all you need to do is check if they are equal to each other or not. If they are equal then String is palindrome or not. You can write this reverse() function by using either for loop or by using recursion.

How to pause Thread in Java using Sleep() and TimeUnit Example

There are multiple ways to pause or stop the execution of currently running thread, but putting the thread into sleep state using Thread.sleep() method is the right way to introduce pause. Some people would say, why not use wait and notify?. Using those methods just for pausing thread is not good. Those are the tools for a conditional wait and they don't depend on upon time. A thread blocked using wait() will remain to wait until the condition on which it is waiting is changed. Yes, you can put timeout there but the purpose of wait() method is different, they are designed for inter-thread communication in Java. By using sleep() method, you pause the current for some given time. You should never use sleep() in place of wait() and notify() and vice-versa. There is another reason why to wait and notify should not be used to pause the thread, a they need lock. You can only call them from a synchronized method or block and acquire and release a lock is not cheap.

How to format numbers in Java? - NumberFormat Example

You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them. Mostly numbers which are used to represent monetary value e.g. price, amount etc requires a comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollars then you would like to see it as 1,000,000 rather than 1000000. Clearly the first one is more readable the second one. Of course, you can further format to add currency based upon locale, but this tutorial is not about that. In this tutorial, we are just looking to format numbers and group them. Its second part of my number formatting article, in the first part you have learned how to format floating point numbers in Java and in this article shows step by step example to group numbers and add commas between them.

Can you Overload or Override main method in Java?

One of the common doubt among Java beginners while learning overloading and overriding is, whether it's possible to overload main in Java ? Can you override the main method in Java? How will JVM find if you change the signature of the main method as part of method overloading? etc. These are a good question and shows curiosity and application of knowledge of students, so if you are the tutor you must answer these questions. The short answer to, can we overload the main method in Java is Yes, you can overloading, nothing stops from overloading, but JVM will always call the original main method, it will never call your overloaded main method. we will learn this in little more detail later, now coming to next question, can you override the main method in Java? the answer is No because main is a static method and static method cannot be overridden in Java.