Pages

One of the common question from programming interviews is, what is the difference between a Thread and a Process? Well, the main difference between them is that a Process is a program which is executing some code and a thread is an independent path of execution in the process. A process can have more than one thread for doing independent task e.g. a thread for reading data from disk, a thread for processing that data and another thread for sending that data over the network. This technique to improve throughput and better utilize CPU power is also known as multi-threading. Technically, most significant difference between thread is address space and context switching. All thread from a process share same address space but a process has their own address space. Similarly, context switching between process is more expensive than context switching between threads.

I use Oracle's virtual machine, Virtualbox to run the Linux operating system from my Windows machine. It's the most simple way to have two operating system in your laptop or PC. Since I run most of Java program in Linux, VirtualBox gives me a nice interface to run UNIX commands right from Windows box. This blog post is about the mounting of shared folder failed error in Oracle's Virtualbox VM. It was working fine day before yesterday and now, after I restarted my virtual box and tried to mount my shared folder, I was greeted by this error: "/sbin/mount.vboxsf: mounting failed with the error: Protocol error". I was using the following command to mount my shared folder on VirtualBox:

$ mount -t vboxsf mountfolder /home/devInHost/mountfolder

I was running Oracle's VirtualBox 4.1 version with the guest operating system as RedHat Linux and host OS as Windows 8.

The instanceof operator in Java is used to check if an object belongs to a particular type or not at runtime. It's also a built-in keyword in Java programming language and mostly used to avoid ClassCastException in Java. It is used as safety-check before casting any object into a certain type. This operator has a form of object instanceof Type and returns true if the object satisfies IS-A relationship with the Type i.e. object is an instance of class Type or object is the instance of a class which extends Type or object is an instance of a class which implements interface Type. Once an object passed the instanceof check, it's safe to type-cast into that type, without worrying of java.lang.ClassCastException.

I always have a strong interest in knowing great peoples of my field i.e. programming. Knowing about them, following them and reading them not only gives you immense knowledge but the motivation you need to excel in what you are doing. It's motivation, not the knowledge that will propel your career. Knowledge is useless without motivation because knowing is not enough, you need to apply that knowledge, and without motivation, you just can't do that. There are times when the programmer's also felt tired and bored. These are the times when you spent hours constantly looking at the computer screen, clicking here and there, surfing the net without doing anything. That's the total waste of time and it's the result of poor motivation. If you are motivated then you will constantly work towards improving your code, writing more unit tests, creating better documentation and spending some time retrospecting, how could you have done better.

String.intern() method can be used to to deal with String duplication problem in Java. By carefully using the intern() method you can save a lot of memories consumed by duplicate String instances. A string is duplicate if it contains the same content as another string but occupied different memory location e.g. str1 != str2 but str1.equals(str2) is true. Since String object consumes a large amount of heap memory in average Java application, it makes sense to use intern() method to reduce duplication and take advantage of String pool feature provided by Java. You can use intern() method to intern a String object and store them into String pool for further reuse.

For example, when you create a String literal e.g. "abc", it's automatically stored in String pool, but when you create a new String object e.g. new String("abc"), even though it's same String, a new object at a different memory location is created. This is a duplicate String.

By calling the intern() method on this object, you can instruct JVM to put this String in the pool and whenever someone else creates "abc", this object will be returned instead of creating a new object. This way, you can save a lot of memory in Java, depending upon how many Strings are duplicated in your program.

You can use String.split() function or StringTokenizer class to split a comma separated String in Java. Since splitting a String is a very common functionality, Java designers have provided a couple of split() method on java.lang.String class itself. These split() function takes a regular expression and split the String accordingly. In order to parse a comma delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java.util.regex) to do its job. If you are not very familiar with the regular expression than you can also use StringTokenizer class, which can also split a comma delimited String but StringTokenizer is an old class and not recommended and you should try to use the split() function from java.lang.String class, as any performance improvement will likely to happen on this method than the StringTokenizer class. Let's see a couple of examples to split a comma separated String in Java. You can also see Java Regular Expressions, taming the java.util.regex engine to learn the full power of Java regular expression.

If you are preparing for Java interviews then apart from blogs and articles, you should also take help of books specially written for Java interviews. Though nothing can substitute true job experience but the interview is little bit different beast. Even if you have a good experience, if you are not going for exact same profile job then you can expect hell lot of questions from vast topics of Java domain, which you might not have heard before. Java developers usually appear for two kinds of interviews, first for core Java development role where the focus is mostly on core Java concepts like multi-threading, concurrency, design patterns, OOP, error handling, collections, JVM internals, GC and Java performance tuning. Second kind of Java interviews for Java EE or Java web development role where the focus is mostly on Java EE related technologies e.g.

In this article, I am going to some frequently asked Microsoft Interview Questions for their Software Development Engineer role. I am mostly sharing technical questions which are based upon Data structure and Algorithms, and Software design. They don't put any restriction on any programming language, which means you are free to solve these problems using C, C++, Java or Python. If you are preparing for Microsoft Interview then these questions can give you some idea about the level of knowledge you need to clear the interview. Regarding how to prepare? You can take help from standard data structure algorithm books or you can use cracking the code interview book, which contains frequently asked questions from Google, Amazon, Apple, Facebook and, of course, Microsoft. For more comprehensive preparation see the recommended books at the bottom of this article.

Core Java Interview Question AnswerThis is a new series of sharing core Java interview question and answer on Finance domain and mostly on big Investment bank.Many of these Java interview questions are asked on JP Morgan, Morgan Stanley, Barclays or Goldman Sachs. Banks mostly asked core Java interview questions from multi-threading, collection, serialization, coding and OOPS design principles. Anybody who is preparing for any Java developer Interview on any Investment bank can be benefited from these set of core Java Interview questions and answers. I have collected these Java questions from my friends and I thought to share with you all.

Recently I received an email from one of my readers that he is not getting enough interview calls though he was applying for every possible job he could from Job portals like Monster.com and Naukri.com. I asked him to send his resume to me and within 30 seconds of opening his CV, I know why he was not getting calls. Though he has right skills and some experience, his resume was not up-to-the-mark, and I am sure it get filtered by either non-technical people, junior HR or project managers. I have been interviewing people from last 10 years and I have involved in every step of conducting a programming job interview, starting from making job description, filtering resume, taking phone interviews, preparing written test papers and conducting face-to-face interviews.

This is the second article about calculating 2nd highest salary in SQL. In the first part, you have learned how to find the second highest salary in MySQL, SQL SERVER and by using ANSI SQL, which should also work in all database which confirms ANSI standard e.g. PostgreSQL, SQLLite etc. In this part, I will show you how to find the 2nd maximum salary in Oracle and SQL SERVER using ROW_NUMBER(), RANK() and DENSE_RANK() method. These are window function in Oracle, which can be used to assign unique row id, or rank to each row based on any column and then select the right row. For example, to calculate the 2nd highest salary, we can create row numbers using ROW_NUMBER() function over salary and then get the second row, which would be your 2nd maximum salary. Though these ranking functions handles duplicates differently, so depending upon whether your table has the duplicate salary, you need to choose either ROW_NUMBER(), RANK() or DENSE_RANK(), which handle duplicate differently. This is also one of the most frequently asked SQL Interview questions for your reference.

In Linux, many times, you want to find out the PID of a process which is listening on a port e.g. if multiple tomcat servers are running on a host then, how do you find the PID of the tomcat listening on port 8080? There are many UNIX commands to find the process using a specific port, but I'll share what I use. I always use the netstat command with -p option, which displays process id of the process listening on a port. Btw, netstat is not the only command to find all processes using a particular port, you can also use lsof command for the same purpose. If you remember, we have used lsof earlier to find all the processes accessing a file but it can also be used to find all processes accessing a specific port. You will see the example of both netstat and lsof commands in this article to find PID of process listening on a specific port in Linux.

In order to do well on Java certifications, you need good books and a reasonable number of practice questions before you go for exams. Practice questions and mock exams will help you to assess your topic-wise preparation level and help you to identify your strong and weak areas. Based on the result of the mock exams, you can concentrate on areas where you lack expertise e.g. multi-threading is one of the tricky areas. It will also expose you to exam patterns and different types of questions you can expect in examination e.g. multiple choice questions, rearranging code, fill in the blanks etc. Though I highly recommend commercial exam simulators like Whizlabs and Enthuware, I also suggest you take advantage of many mock questions which are freely available.

You can use LEN() function to find the length of a String value in SQL Server, for example, LEN(emp_name) will give you the length of values stored in the column emp_name. Remember this is different than the length of the actual column which you specify while creating table e.g. emp_name VARCHAR(60). To give you an example, you have a column called emp_name VARCHAR(60), which means the length of this column is 60 character, it can hold names with maximum 60 character long, but not all names are 60 character. In this SQL SERVER tutorial, I will teach you how to use the LEN() function to find out actual length or number of character in a VARCHAR or CHAR field.

You can use either curl or wget command to send HTTP request from UNIX or Linux operating system. Both commands allow you to send GET and POST request, which means you can also call REST web services. I have a Java web application, which runs on Linux and exposes WebServices. I was writing a UNIX script to download In some data from that web service when I hit by the question, how do I make an HTTP call from UNIX? What is the UNIX command should I use? If you are also facing the same question, then you have come to right place. Basically, you can use two UNIX commands to make the HTTP request, wget, and curl. You can use curl and wget to send both GET and POST HTTP request. My use case was rather simple, I just need to make a GET call to web service to download the data, but these two commands are very powerful and provide many different options to interact with the web using HTTP right from the shell.

We often need to replace NULL values with empty String or blank in SQL e.g. while concatenating String. In SQL Server, when you concatenate a NULL String with another non-null String the result is NULL, which means you lose the information you already have. To prevent this, you can replace NULL with empty String while concatenating. There are two ways to replace NULL with blank values in SQL Server, function ISNULL() and COALESCE(). Both functions replace the value you provide when the argument is NULL e.g. ISNULL(column, '') will return empty String if the column value is NULL. Similarly, COALESCE(column, '') will also return blank if the column is NULL.

Code Academy has now released their full Java course and within days, almost 60K+ students have already registered. Does it say anything about the popularity of Java? Given Java provides the really good prospect of getting a job and there are more than one reasons to learn Java, I am not surprised with a number of students registered. Code Academy has always been a superb source to learn new programming language or technology from the start. I first started using it for learning JavaScript and used it a couple of months back to improve my UNIX command skills.

A binary search tree or BST is a popular data structure which is used to keep elements in order. A binary search tree is a binary tree where the value of a left child is less than or equal to the parent node and value of the right child is greater than or equal to the parent node. Since its a binary tree, it can only have 0, 1 or two children. What makes a binary search tree special is its ability to reduce the time complexity of fundamental operations like add, remove and search, also known as insert, delete and find. In a BST, all these operations (insert, remove and find) can be performed in O(log(n)) time. The reason for this improvement in speed is because of the unique property of binary search tree, where for each node, the data in the left child is less than (or equal) and the data in the right child is greater than (or equal) to the data in said node.

Last Updated Date: 30th October 2015
Time is changing and so is Java interviews. Gone are the days, when knowing the difference between String and StringBuffer can help you to go through the second round of interview, questions are becoming more advanced and interviewers are asking more deep questions. When I started my career, questions like Vector vs Array and HashMap vs Hashtable were the most popular ones and just memorizing them gives you a good chance to do well in interviews, but not anymore. Nowadays, you will get questions from the areas where not many Java programmer looks e.g. NIO, patterns, sophisticated unit testing or those which are hard to master e.g. concurrency, algorithms, data structures and coding.

It's been a long time, I wrote anything related to FIX protocol, my last article was about FIX protocol dictionaries, also known as Fixionnary, one of the most important tools of the trade for Java developers and support personnel working in FIX. Today, I am going to share another useful tool called FIX Log Viewer, which allows you to view FIX engine logs in a much more readable format.

Double brace initialization is a Java idiom to initialize a Collection like a list, set and map at the time of declaration. At times, you need a list of fixed elements e.g. supported products, supported currencies or some other config, and on the spot initialization reduces line of code and improves readability. Double brace initialization idiom becomes popular because there is no standard way to create and initialize Collection at the same time in Java. Unfortunately, unlike another language, Java doesn't support collection literals yet. Due to this limitation, creating an unmodifiable List with small numbers of elements requires many lines of code involving creating list, repeatedly calling add() method to add those elements and then finally wrapping it into unmodifiable list as shown below :

I had installed SQL SERVER 2014 Express edition and I was trying to connect to SQL SERVER from Java program using JDBC, but I was repeatedly getting following error:

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "connect timed out. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".Error while closing connection !!null

From the first round to HR round, from telephonic to face-to-face, in almost all kind of programming interviews, there will be a time when Interviewer will give you a chance to ask questions. Many programmers are too concern about asking questions, and they politely decline ; Well it's your chance to learn about the Job you are going to do, and you shouldn't let this opportunity goes away. The interviewer, also judges you by your questions; a good, thoughtful, positive question can create the great impression on Interviewer's mind. It also shows that the interest of a candidate for a Job.

Hello Guys,
How are you? Hope you are doing well.
It's been 5 years since I have started Javarevisited. In last five years, I have worked hard to make Javarevisited a good resource to prepare for Java interviews, and to make it even more useful, I am inviting you, my readers, to share your Interview experience with us, the Javarevisited community. If you like Javarevisited and think that it has helped you in past, and you want to give something back to the community, then it's time to share your own interview experience with us.

You often need to convert java.util.Date to java.sql.Date if you are storing dates in database e.g. SQL SERVER or MySQL. Since JDBC has their own data types for date and time e.g. java.sql.Date, java.sql.Time and java.sql.TimeStamp to match with database date, time and date-time types, you cannot pass a java.util.Date directly. All methods which are suppose to store dates e.g. setDate(paramName, paramValue) expects java.sql.Date, so it becomes essential to know how to convert java.util.Date to java.sql.Date in JDBC. You would be surprised to know that java.sql.Date is a subclass of java.util.Date and all it does is suppress or remove time-related fields from java.util.Date.

Many times we want to reset an ArrayList for the reusing purpose, by resetting we mean clearing it or removing all elements. There are two ways to reset an ArrayList in Java, by using clear() method or calling removeAll(). If your ArrayList is small enough e.g. contains only 10 or 100 elements then you can use any of these two methods without worrying too much, but, if you have a huge list of lots of objects e.g. an ArrayList containing 10M entries, then choice of clear() vs removeAll() can make a huge difference in performance of your Java application. Sometimes it's even better to create a new ArrayList instead of resetting the old one, especially if resetting takes a long time, but this also has a caveat, you need to make sure that old ArrayList is eligible for garbage collection, otherwise there is a huge risk of java.lang.OutOfMemoryError: Java Heap Space.

Java 8 has introduced a new way to loop over a List or Collection, by using the forEach() method of the new Stream class. You can iterate over any Collection e.g. List, Set or Map by converting them into a java.util.sttream.Stream instance and then calling forEach() method. This method performs given operation on every element of Stream, which can be either simply printing it or doing something else. Since stream can be sequential or parallel, the behavior of if this method is not deterministic if used with a parallel stream. One more thing to remember about the forEach() method is that it's a terminal operation, which means you cannot reuse the Stream after calling this method. It will throw IllegalStateException if you try to call another method on this Stream.

Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write a lot of boilerplate code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on. Of course, JDK 1.5's Scanner class did provide some breathing space but it was still not as simple as it should be, like in Python or Ruby. By using Java 7 new File API and Java 8's new features like lambda expression and stream API, Java is now close to Python or other utility languages, when it comes to reading the file into String.

Problem : You are getting java.lang.ClassNotFoundException exception complaining that Spring's DispatcherServlet class is not available in the classpath. This error is coming while running a Spring MVC based Java application from Eclipse and Tomcat as Server (running inside Eclipse IDE itself). You have either included spring framework JAR files manually by yourself or you are using Maven to download and manage dependent JAR files. Here is the stack trace of this error :

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:525) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:507) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:126) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1099) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1043) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4957

There are two types of variables in Java, primitive and reference type. All the basic types e.g. int, boolean, char, short, float, long and double are known as primitive types. JVM treats them differently than reference types, which is used to point objects e.g. String, Thread, File and others. Reference variables are not pointers but a handle to the object which is created in heap memory. The main difference between primitive and reference type is that primitive type always has a value, it can never be null but reference type can be null, which denotes the absence of value. So if you create a primitive variable of type int and forget to initialize it then it's value would be0, the default value of integral type in Java, but a reference variable by default has a nullvalue, which means no reference is assigned to it.

Yesterday one of the junior from my team came to me asking about how do you I convert a float variable into long or int? He was storing some values coming from another system in the database and only wanted to store value before the decimal point e.g. he was getting "3.144" and he want to convert it to "3" to store into database. Good thing was that API was returning a float primitive value and you don't need to convert a String to float etc. There are 3 ways to convert a float value into long or int in Java, but we will only focus on long part. You can write the Java program by following tips to convert float to an int by replacing long method to their int counterpart. The first way is to auto-box float primitive into Float object and call the longVale() method and another way is simply cast a float to long or int to get rid of decimal points.

@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Overrideand @Deprecated in Java 1.5. @SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated. You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.

You can loop over a two-dimensional array in Java by using two for loops, also known as nested loop. Similarly to loop an n-dimensional array you need n loops nested into each other. Though it's not common to see an array of more than 3 dimension and 2D arrays is what you will see most of the places. It's one of the most useful data structure in the programming world. You can use a two-dimensional array to make finite state machine (FSM) solve state based problems, you can use a 2D array to create board games like Chess, Sudoku and Tic-Tac-To and you can even use a two-dimensional array to create 2D arcade games e.g. Tetris, Super Mario Bros and so on. Whatever you see on your screen is nothing but a 2D array which is populated using tiles.

If you are a C++ Programmer, now learning Java then you will find a lot of similarity between two of the most popular object-oriented programming languages e.g. both support Abstraction, Encapsulation, Class, Object and other OOP concepts. But, they are some subtle differences as well, e.g. both Java and C++ have a constructor and they work the same way in Java as they do in C++, but the way they are called is different. For example, In Java, a constructor must be called by using the new() operator, there is no other way to explicitly call the constructor while creating an object, but in C++ you can do it without new operator. This is a good interview question for programmers who knows both Java and C++.

Though both SOAP and RESTful web services allow a client to query the server for some information, but the way they are implemented and used is quite different. The main difference between SOAP and REST is that former provides a standard of communication between client, server and other parties and has restricted a set of rules and format, while REST leverages the ubiquity of HTTP protocol, in both client and servers, to allow them to communicate with each other regardless of their implementation. In short, getting data from a RESTful web service requires less headache then getting data from a SOAP web service. Since everybody is familiar with HTTP requests like GET or POST, it's easy to understand and correlated how RESTful web services are working and which URL of REST web service provides what kind of information. In SOAP, you need to understand lengthy WSDL document to find out right methods and the right way to call them.

Unsupported major.minor version 51.0 error comes when you run a class file created using Java 1.7 (major version 51.0) into a lower JRE version e.g. JRE 6, 5 or 4. There are two ways to solve this problem, first make sure you run your Java program in same or higher version of JRE, on which it has compiled, and second use cross-compilation option to create a class file compatible to a lower JRE. You can use javac -target option to create a class file for all JRE up-to-the JDK version you are using for compilation. For example, if you are compiling your Java source file into JDK 1.7 then you can create class files to run on JDK 1.1, 1.2, 1.3, 1.4 , 1.5 and 1.6 version, but you cannot create class files compatible with Java 1.8. When you compile a Java source file, it creates a class file and add the class file version into it. In order to run that class file, your JRE must understand that version. When JRE or JVM which is running the class doesn't able to understand the class file version they throw java.lang.UnsupportedClassVersionError: XXX : Unsupported major.minor version 51.0 error, where XXX is the name of your class which has an incompatible version.

Factorial of numbers greater than or equal to 13 cannot be found using primitive int data type as shown in our earlier factorial solution due to overflow. These factorials are too large to fit in an int variable, whose maximum value is just 2147483647 (2^31 -1). Even if we use the long data type, factorials greater than or equal to 21 will generate an overflow. To find the factorial of anything above 21, you need to use the BigInteger class from java.math package. As the name suggests, BigInteger class is designed to hold really large integer value, something which is even bigger than the maximum value of long primitive e.g. 2^63 -1 or 9223372036854775807L. You also need to change the way we calculate factorial for a smaller number. You can not use recursion to calculate factorial of a larger number instead we need to use for loop for that.

The java.util.Map is one of the most important interfaces from Java Collection Framework. It provides hash table data structure functionality by its implementations like HashMap, Hashtable,LinkedHashMap and a little bit of sorting with the TreeMap. So if you are looking to store key-value pairs in Java program, you have a wide range of choices available depending upon your requirement. The main difference between LinkedHashMap, TreeMap and HashMap comes in their internal implementation and specific features, which makes them useful in certain scenarios. For example, the HashMap is a general purpose Map (hash table data structure), which should be used whenever you need a hashing-based data structure for storing your mappings (key-value pairs).

StackOverFlow is great place to look for help, learn and participate, but it's also a great place to taste some real entertainment, contributed by programmers from all over the world. Though, due to strict policies of stackoverflow.com, most of entertaining post either are either gets closed or deleted, some of them remained to entertain programming community. Being a regular reader of StackOverFlow from long time, I have found couple of threads which are truly amazing, and has lot's of funny and entertaining content. Here I am going to share 5 of my favorite StackOverFlow posts, which I suggest you to read, if you get bored or you have some time to kill. By the way, don't forget to leave comments and let us know which is your favorite funny and entertaining threads in StackOverFlow.

For a change, this article is not for candidates who are preparing for interviews, but for those programmers who are responsible for taking interviews. At some point in your career as a programmer, you will have the responsibility to hire developers for your company. This is a big responsibility and your ability to select right candidate will directly affect your company's future. This is more visible in small companies than the larger organization where a pool of interviewer exists. In a start-up, if you are a technical lead and responsible for hiring, it's a tough job. You have to hire right candidate which fits in companies culture and competent enough to do the job they were hired for. To be frank, conducting interviews is as hard as giving interviews.

How to find all permutation of a String using recursion is one of the tricky coding questions from Programming job interviews. I have first seen this question in my college exam when we were asked to code the solution using C or C++ language. Since then I have seen this question many times at various written tests and Java interviews for a junior developer position. It does not only serve as a good question to check whether the candidate understands recursion but also its one of the better Java programming exercise for beginners. Typically, you will be asked to write a method, which accepts a String and print all permutations or may return all permutations in a List for a junior developer position. Depending upon the company you are going for an interview, they may ask you to code on IDE like Eclipse or NetBeans, or simply write code in plain paper, so be prepared for both.

for loop has come a long way in Java 8 with new forEach() method in java.util.stream.Stream class. In this article, we will take a look at the journey of for loop in different versions of Java programming language. for loop is there from the very beginning of Java i.e. JDK 1.0. Almost all Java programmers have used the classical for() loop, as it is also an essential programming construct, I guess just next to if-else, but when the foreach loop or as some people call it enhanced for loop was introduced in JDK 1.5, everything changed from looping over Collection and array perspective. Yesterday's popular looping construct become old and ugly and more elegant solution took over. It was shorter, cleaner and less error prone, what else you need at that time.

ByteBuffer is one of the important class of Java NIO API. It was introduced in java.nio package on JDK 1.4, it not only allows you to operate on heap byte arrays but also with direct memory, which resides outside the JVM. There are mainly three types f ByteBuffer, Direct, Non-Direct and mapped byte buffers. You can create both direct and non-direct buffers using java.nio.ByteBuffer class, while MappedByteBuffer is a subclass of ByteBuffer, which is created by FileChannel.map() method, to operate on memory mapped file. The main difference between direct and non-direct byte buffers are there memory location, non-direct byte buffers are just a wrapper around byte array and they reside in Java Heap memory while direct byte buffer is outside of JVM and memory is not allocated from the heap.

If you remember, I have updated to Windows 10 yesterday and blog about the problem I was facing with respect to clarity of text and blurriness on Chrome and Firefox browser e.g. text was turned white to some places and it wasn't pleasant working in the browser. There were few other issues, which prompted me to revert back to Windows 8.1 update, which was the version I was running before upgrading to Windows 10. Though Windows 10 has lots of good feature in terms of improved search, security and start menu, I didn't adjust it well. Since I don't have time to play around different visual settings and other things, I decided to roll back to Windows 8 version.

Today morning, I updated My HP Laptop to Windows 10. The first impression was great, crystal clear images, better wallpaper, better themes, better welcome screen and improved start menu and task bar at the right-hand corner. But when I open Chrome and Firefox the text look faded, more bright and contrast was not perfect. Since I had not changed anything, I suspect this is the Windows 10 default settings which are causing the problem. I knew it before because I had also faced similar issues when I was moved from Windows XP to Windows 8 and then Windows 8.1 update. If you are facing the same problem where your Chrome, Firefox are not looking clear, instead looking blurry and faded then you need to adjust your Laptop's screen brightness, contrast, and gamma.

Data Structure and Algorithms books are often taught as textbooks in various universities, colleges and Computer Science degree courses, yet, when you put programmers in a situation, where they need to find and decide, which data structures and algorithms to use to solve a problem, they struggle. I have seen this, and I think one reason of this is perspective. When you read something as a textbook and your perspective is just to do well in the exam, you might not be thinking about learning and applying that knowledge to real-world problems. Since data structures and algorithms are the core of any programming problem, it becomes extremely important for programmers to master them even if you have learned well during academics.

If you are not running on Java 8, then there are two ways to calculate the difference between two dates in Java in days, either by using standard JDK classes e.g. java.util.Date and java.util.Calendar or by using the joda-time library. Unfortunately, Java's old Date and Calendar API is buggy and not intuitive, so many of us by default use Joda for all date and time arithmetic. In this example, you will learn how to find the number of days between today and any date entered by a user using Joda, as well as without using any third party library. When I first time face this problem, I thought what's a big deal about finding the difference between dates? If you can convert Date to milliseconds then finding a number of days, months or years are just a matter of simple arithmetic, but I was WRONG. I was not thinking about real world date and time nuisance like leap seconds, leap years, and daylight saving time.

java.sql.SQLException: No suitable driver found for
There are two ways to connect Microsoft SQL Server from Java program, either by using Microsoft's official JDBC driver (sqljdbc4.jar), or by using jTDS driver (jtds.jar). This error comes when your supplied database URL didn't match with the JDBC driver present in the CLASSPATH. Many programmers who usually use jtds.jar, makes a mistake while using sqljdbc4.jar by adding "microsoft" in JDBC URL. That makes URL invalid and JDBC API throws "java.sql.SQLException: No suitable driver : sqljdbc4.jar" error.

Java 8 has added a new method called lines() in Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed. So, if you have a huge file and you only read first 100 lines then rest of the lines will not be loaded into memory, which results in better performance. This is slightly different than Files.readAllLines() method (which reads all lines into a List) because this method reads the file lazily, only when a terminal operation is called on Stream e.g. forEach(), count() etc. By using count() method you can actually count a number of lines in files or number of empty lines by filtering empty lines.

Suppose you have an XML file and you just want to read and display the whole file as String in Java, may be for debugging purpose. If you are wondering how to do that in Java, well there are many ways to read XML as String in Java. You can do it in one line if you are fine with using an open source library or you can do it in a couple of lines of code in core Java as well. Since an XML file is also a file, you can use BufferedReader or FileInputStream to read the content of an XML file as String by using the techniques, I have discussed in my earlier post 3 ways to convert InputStream to String in Java. But this post is about a new library called jcabi-xml which makes working with XML file really easy. You can parse the XML file using XPath expression, you can do XSL transformation, XSD schema validation and you can even parse whole XML file as String in just a couple of lines of code.

You can convert a character e.g. 'A' to its corresponding ASCII value 65 by just storing it into a numeric data type e.g. byte, int or long as shown below :

int asciiOfA = (int) 'A';

Here casting is not necessary, simply assigning a character to integer is enough to store ASCII value of character into an int variable, but casting improves readability. Since ASCII is 7-bit character encoding, you don't even need an integer variable to store ASCII values, byte data type in Java, which is 8 bits wide is enough to store ASCII value of any character. So you can also do like this :

In a nice gesture, Oracle has announced 20% discount on any Java certification to celebrate 20 years of Java. Which means now you can get your Java SE certification at 20% discount, this is almost a saving of almost 50 USD. This is really exciting to all Java developers who are preparing for Java SE 8 certification, 1Z0-808 (Oracle Certified Associate, Java SE 8 Programmer) or certified Java developers who are looking to upgrade their certification for Java SE 8. This discount is available to ANY Java certification, including OCPJP 6, OCAPJP 7, OCPJP 7 and OCAJP 8. Now, the big question, how do you get this discount? Not much, just choose the exam you want to take and register for it as shown below, but don't get late. This offer is only valid till 31st December 2015.

Problem : Write a Java program to print the duplicate words from a given statement e.g. if given String is "Java and JavaScript are totally different, JavaScript follows Java" then your program should print "Java" and "JavaScript" because those two are 2 duplicate words from given String. You need to consider all cases e.g. given String can be null, empty, may or may not contain any duplicate words, but for simplicity, you can assume that sentence will always in English and only use ASCII characters, alphabets, and numerals, no special character. It's better to get the requirement right of the problem in the beginning even if the interviewer doesn't tell you everything. Directly jumping into solution without asking a couple of questions may not go well with many interviewers who looks for detail oriented candidates.

Java 8 now directly allows you to do GROUP BY in Java by using Collectors.groupingBy() method. GROUP BY is a very useful aggregate operation from SQL. It allows you to group records on certain criteria. How do you group by in Java? For example, suppose you have a list of Persons, How do you group persons by their city e.g. London, Paris or Tokyo? Well, we can do that by using a for loop, checking each person and putting them on a list of HashMap with the same city, but in Java 8, you don't need to hack your way like that, you have a much cleaner solution. You can use Stream and Collector which provides groupingBy() method to do this. Since its one of the most common way to aggregate data, it has a real benefit, coupled that with the various overloaded version of groupingBy() method which also allow you to perform grouping objects concurrently by using concurrent Collectors.

java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver exception comes in Java 8 because it has removed the JDBC ODBC bridge driver class "sun.jdbc.odbc.jdbcodbcdriver" from JDK and JRE. This class is required to connect any database using Object database connectivity driver e.g. Microsoft Access, but unfortunately you cannot use it from JDK 8 onward. In order to solve this error, just use Jackcess library or a commercial driver like HXTT. Normally, in pre Java 8 world, java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver error comes when you try to connect to Microsoft Access database from Java using JDBC and JDBC ODBC bridge driver is not available in classpath. If you remember, In order to open SQL connection to database, first step is to load and register the driver. In order to load driver, we use Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); and this method throws java.lang.classnotfoundexception sun.jdbc.odbc.jdbcodbcdriver, if ClassLoader is not able to find the requested class (sun.jdbc.odbc.JdbcOdbcDriver) in CLASSPATH. In order to connect to MS Access, we need type 1 JDBC driver, also known as JDBC ODBC bridge driver and the class in question, JdbcOdbcDriver is driver implementation to connect to Open database connectivity driver installed in machine.

Most of the Java interview questions on ArrayList asked to freshers or Java developers with 1 to 2 years experience is just simply how to do task e.g. how to sort arraylist, how to serach element, how to remove an element using iterator etc. Since, I have written lots of Java tutorials on ArrayList, covering many general purpose tasks e.g. how to create an object of ArrayList and initialize to how to sort ArrayList in ascending and descending order etc. On request of my readers, I am creating this mega list of ArrayList tutorials, which will help you to learn everything about ArrayList class. These tutorials are great for beginners and even experienced Java developers can learn a trick or two.

Strategy design pattern is based upon open closed design principle, the 'O' of famous SOLID design principles. It's one of the popular pattern in the field of object-oriented analysis and design along with Decorator, Observer and Factory patterns. Strategy pattern allows you to encapsulate possible changes in a process and encapsulate that in a Strategy class. By doing that your process (mainly a method) depends upon a strategy, higher level of abstraction than implementation. This makes your process open for extension by providing new Strategy implementation, but closed for modification, because the introduction of a new strategy doesn't require a change in a tested method. That's how it confirms open closed design principle.

I have read somewhere that programmer should learn a new programming language every year ( I think it's code complete, not sure, though), but if you cannot do so, I suggest to at least learn following five programming language to do well in your career. Everybody loves polyglot programmer and an all rounder who is versatile enough to write a quick script and can also write complex Java programs. In fact, it's almost mandatory for a senior developer to learn more than one language. Interviewers are giving more attention to a programmer who has good experience with multiple languages e.g. C++ and Java goes quite well, so is Python and Java. I personally like programmers who have strong experience on either C++ or Java and can write scripts in groovy, Perl or Python.

Fibonacci series is a great example of Recursion and how the use of recursion can result in a clear and concise solution. That's why whenever asked about writing a Java program to get a Fibonacci numbers or print the Fibonacci series of certain numbers, it's quite natural for programmers to resort to recursion. Interviewer often challenged this practice by asking candidates to implement Fibonacci series without using recursion. Yes, you read it right, you can't use recursion and this is what you will learn in this article. If you have attended your programming classes regularly then you may know that many recursive algorithms also has their iterative counterpart which uses loops instead of recursion or calling itself . We will take advantage of that concept to devise a solution of this problem.

This error comes when you try to connect to Microsoft SQL Server database from Java program but the required JDBC driver is not available in Classpath or driver is available in CLASSPATH but the class loader is not able to find it due classpath intricacies. Depending upon your situation, a solution could be as simple as downloading any of sqljdbc.jar, sqljdbc4.jar or sqljdbc41.jar, based upon the Java version you are using and adding them into CLASSPATH as set CLASSPATH = %CLASSPATH%; (path to Microsoft JDBC driver) in Windows. BTW, in most of the cases "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver" comes because of classpath intricacies. For example, if your Java program is using -cp or -classpath option but you added the JAR into CLASSPATH environment variable or vice-versa.

In this Java tutorial, you will learn how to write a program to convert Fahrenheit to Celsius in Java. Fahrenheit is a thermodynamic temperature scale, where the freezing point of water is 32 degrees Fahrenheit (°F) and the boiling point of water is 212°F (at standard atmospheric pressure). This puts the boiling and freezing points of water exactly 180 degrees apart. Therefore, a degree on the Fahrenheit scale is 1/180 of the interval between the freezing point and the boiling point of water. Absolute zero is defined as -459.67°F. If you know, in Celsius scale, the freezing point of water is at 0ºC and the boiling point of water is at 100ºC. By using these facts, you can easily deduce a formula to convert Fahrenheit temperature into Celsius.

"java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path" error comes when you try to connect to Oracle 11g database using OCI (thick) driver by using tns name, but the ocijdbc11.dllfile is not available in PATH or java.library.path environment variable. ocijdbc11.dll is a native library and if you know Java searches native library in PATH or a location specified by java.library.path system property, if it doesn't find the dll, then it throws java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path error. This dll is usually found in C:\Programs\Oracle\ora11g\bin\ocijdbc11.dll, but it could vary depending upon your Oracle installation.

You can use wait, notify and notifyAll methods to communicate between threads in Java. For example, if you have two threads running in your program e.g.Producer and Consumer then producer thread can communicate to the consumer that it can start consuming now because there are items to consume in the queue. Similarly, a consumer thread can tell the producer that it can also start putting items now because there is some space in the queue, which is created as a result of consumption. A thread can use wait() method to pause and do nothing depending upon some condition. For example, in the producer-consumer problem, producer thread should wait if the queue is full and consumer thread should wait if the queue is empty.

TL;DR Main difference between dependency injection and factory pattern is that in the case of former dependency is provided by the third party (framework or container) while in the case of later dependency is acquired by client class itself. Another key difference between them is that use of dependency injection result in loosely coupled design but the use of factory pattern create a tight coupling between factory and classes which are dependent on the product created by the factory. Though both Dependency Injection and Factory pattern look similar in a sense that both creates an instance of a class, and also promotes interface driven programming rather than hard coding implementation class; But, there are some subtle differences between Factory pattern and dependency injection pattern.

A String is said to be Palindrome if it is equal to itself in reverse order. You can use this logic to check if String is Palindrome or not. There are two common ways to find if a given String is Palindrome or not in Java, first by using for loop, also known as iterative algorithm and second by using recursion, also known as recursive algorithm. The crux of this problem lies in how do you reverse String in Java? because once you have the String in reverse order, problem reduced to just comparing itself with the reversed String. If both are equal then given String is Palindrome otherwise it's not. Also whether your solution is iterative or recursive will also determine by implementing this logic. If you reverse String using for loop then it become an iterative solution and if you reverse String using recursion then it become a recursive solution. In general, recursive solution are short, readable and more intuitive but subject to StackOverFlowError and that's why not advised to be used in production system. You should always be using iterative solution in production, unless your programming language supports tail recursion optimization e.g. Scala which eliminates risk of StackOverFlowError by internally converting a recursive solution to an iterative one. If you are doing this exercise as part of your Interview preparation then I suggest you to take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions, as title says it contains 150 good questions based upon different topics e.g. String, array, linked list, binary tree, networking etc. A good book for preparing both Java and C++ interview.

java.lang.ClassNotFoundException: org.postgresql.Driver error comes when you are trying to connect to a PostgreSQL database from Java program but Java ClassLoader is not able to find the Driver class "org.postgresql.Driver" required to make the connection. Usually this class is find in PostgreSQL JDBC driver JAR e.g. postgresql-9.4-1201.jdbc41.jar, which is required to connect PostgreSQL server version greater than 9.3 from JDK 1.7 or JDK 1.8, the exact JAR depends upon your PostgreSQL server version, the Java version you are running and JDBC version your are using. Now your problem could be either you don't have that PostgreSQL JDBC driver JAR in your machine or the JAR is not in your classpath, or you might be battling with some classpath intricacies. If you don't have this JAR, then solution of "java.lang.ClassNotFoundException: org.postgresql.Driver" is simple, just download it from PostgreSQL site. Make sure you download the correct version of JDBC driver based upon the PostgreSQL server you are connecting and JVM version of your machine. Once you download that, just put in the lib directory of your Java application e.g. WEB-INF/lib if you are connecting to PostgreSQL from Java Web Application. If you are running in Tomcat, then you can alternatively also put this in tomcat/lib directory, but beware of the difference in the application dependency in WEB-INF/lib or in tomcat/lib. You can also take a look at Practical database programming with Java book by Ying Bai. This books is a comprehensive guide of how to use JDBC in Java to connect to different databases. You will learn right ways of doing things with respect to Java and database.

SQL is one of the most important skill for any programmer be it a Java, C++, PHP or Ruby developer. Almost 95% of the Java applications uses relational database in their back-end and almost all web applications uses database. In recent years, one of the most common way to learn any programming skill is online, at your comfort of office or home and SQL is no different. Learning SQL online has another advantage of quick head start because you don't need to install database and create tables to write some SELECT queries. Once you start writing queries and seeing result, you feel that confidence needed to go to next level, which involves downloading and installing free copy of popular databases e.g. MySQL, SQL Server or Oracle in your machine. From my experience I can say that SQL is easy to learn but difficult to master. You can start writing SQL queries in about an hour or so, but when it comes to write queries to solve real time requirements or for reporting purpose, its not that easy. Practicing SQL online on sites like SQLZoo or SQLFiddle will help you to keep yourself up-to-date. You can also take help from some good SQL books like Head First SQL if you are beginner, head first way is one of the best way to learn SQL.

Java has a very good networking support, allows you to write client server application by using TCP Sockets. In this tutorial, we will learn how to create a simple HTTP Server in Java, which can listen HTTP request on a port let's say 80 and can send response to client. Being an HTTP Server, you can connect to it using your browser e.g. Chrome, Firefox or Internet Explorer. Though HTTP is ubiquitous and present everywhere, Java doesn't have a dedicated API to create and parse HTTP request, there is no in built HTTP client library in JDK. Though there is no short of good open source library e.g. you can use Jsoup to parse HTML and can use Apache HttpClient library for sending GET and POST request right from your Java program. By the way, for those who wants to master network programming in Java, I suggest to read Java Network Programming, 4th Addition by Harold, Elliotte Rusty, its very comprehensive and not only covers both TCP/IP and UDP protocols, which are backbone of internet but also dive deep into the HTTP protocol, including REST, HTTP headers, and cookies. Book is very focused on practical and you will find lot of interesting example related to common networking task e.g. writing multi-threaded servers, using non blocking IO and using low level socket classes.

In last tutorial, you have learned how to parse Excel file in Java and in this Java tutorial, you will learn how to parse CSV file in Java. You can directly parse CSV file in Java without using any third party library, because ultimately its a text file and you can use BufferedReader to read it, but you can also take advantage of good open source library like Apache commons CSV to parse comma separated values. These library makes developer's life easy and provides rich functionality to parse various CSV formats. In real programming world, CSV or comma separated files are used for variety of purpose, including for transporting data from one system to another e.g. FX rates, importing and exporting records from database etc. In CSV files entries are separated by comma, and it may or may not contain header. There are many ways to parse or read CSV files in Java, and if you need to do it on your project, its better not to reinvent the wheel and choose commons csv, but for learning purpose, it's good to know how to do it without using third party library.

There are multiple ways to find duplicate elements in an array in Java and we will see three of them in this program. Solution and logic shown in this article are generic and applies to an array of any type e.g. String array or integer array or array of any object. One of the most common way to find duplicates is by using brute force method, which compares each element of the array to every other element. This solution has the time complexity of O(n^2) and only exists for the academic purpose. You shouldn't be using this solution in the real world. The standard way to find duplicate elements from an array is by using HashSet data structure. If you remember, Set abstract data type doesn't allow duplicates. You can take advantage of this property to filter duplicate elements. This solution has a time complexity of O(n), as you only need to iterate over array once, but also has space complexity of O(n) as you need to store unique elements in the array.

You can also solve producer consumer problem by using new lock interface and condition variable instead of using synchronized keyword and wait and notify methods. Lock provides an alternate way to achieve mutual exclusion and synchronization in Java. Advantage of Lock over synchronized keyword is well known, explicit locking is much more granular and powerful than synchronized keyword, for example, scope of lock can range from one method to another but scope of synchronized keyword cannot go beyond one method. Condition variables are instance of java.util.concurrent.locks.Condition class, which provides inter thread communication methods similar to wait, notify and notifyAll e.g. await(), signal() and signalAll(). So if one thread is waiting on a condition by calling condition.await() then once that condition changes, second thread can call condition.signal() or condition.signalAll() method to notify that its time to wake-up, condition has been changed. Though Lock and Condition variables are powerful they are slightly difficult to use for first timers. If you are used to locking using synchronized keyword, you will using Lock painful because now it becomes developer's responsibility to acquire and release lock. Anyway, you can follow code idiom shown here to use Lock to avoid any concurrency issue. In this article, you will learn how to use Lock and Condition variables in Java by solving classic Producer Consumer problem. In order to deeply understand these new concurrency concepts, I also suggest to take a look at Java 7 Concurrency Cookbook, Its one of the best book in Java concurrency with some good non trivial examples.

Callable interface was added in Java 5 to complement existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution. Callable actually represent an asynchronous computation, whose value is available via Future object. All the code which needs to be executed asynchronously goes into call() method. Callable is also a single abstract method type (SAM type), so it can be used along with lambda expression on Java 8. Both Callable and Future are parametric type and can be used to wrap classes like Integer, String or anything else. When you pass a Callable to thread pool, it choose one thread and execute the Callable. It immediately return a Future object which promises to hold result of computation once done. You can then call get() method of Future, which will return result of computation or block if Computation is not complete. If you don't like indefinite blocking then you can also use overloaded get() method with timeout. Future also allows you to cancel the task if its not started or interrupt if its started. We will see, how we can calculate factorial of large number using Callable and Future in Java. BTW, if you are serious about mastering concurrency API of Java, I suggest you to also take a look at one of the best book on the subject, Java Concurrency in Practice by Brian Goetz. It is one of the book I keep refer whenever I have a doubt or want to refresh my knowledge.