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.

How to get first and last elements form ArrayList in Java

There are times when you need to get the first or last element of an ArrayList. One of the common scenario where you need first and last element of a list is supposed you have a sorted list and wants to get the highest and lowest element? How do you get that? The first element is your lowest and the last element is your highest, provided ArrayList is sorted in ascending order. If its opposite then first element would be the maximum and last element would be the minimum. This is quite easy to do in ArrayList because the first element is stored at index 0 and the last element is on index, size - 1. If you know how to get the size of ArrayList then you can easily get those two values. Just remember, that you need to use size() method and not length, which is used to get the length of array. Earlier we have seen how to get first and last element from linked list and In this tutorial we are going to see an example of how get the last element from ArrayList in Java.

By the way if you are serious about learning Java collection framework in deep and want to master different types of collection classes e.g. List, Set, Map, ConcurrentMap, Queue, Stack, BlockingQueue and other thread safe collections introduced on Java 5 and 6, then I suggest you to take a look at Java Generics and Collection by Maurice Naftalin and Philip Wadler, one of the best books to learn Java Collections.

How to use CyclicBarrier in Java - Concurrency Tutorail

This is the second part of my concurrency tutorial, in the first part, you have learned how to use CountDownLatch and in this part, you will learn how to use CyclicBarrier class in Java. CyclicBarrier is another concurrency utility introduced in Java 5 which is used when a number of threads (also known as parties) want to wait for each other at a common point, also known as the barrier before starting processing again. Its similar to CountDownLatch but instead of calling countDown() each thread calls await() and when last thread calls await() which signals that it has reached the barrier, all thread started processing again, also known as a barrier is broken. You can use CyclicBarrier wherever you want to use CountDownLatch, but the opposite is not possible because you can not reuse the latch once the count reaches to zero. Some of the common usages of CyclicBarrier is in writing a unit test for concurrent program, to simulate concurrency in a test class or calculating final result after an individual task has completed.

Java CountDownLatch Example

CountDowaLatch is a high-level synchronization utility which is used to prevent a particular thread to start processing until all threads are ready. This is achieved by a countdown. The thread, which needs to wait for starts with a counter, each thread them make the count down by 1 when they become ready, once the last thread call countDown() method, then the latch is broken and the thread waiting with counter starts running. CountDownLatch is a useful synchronizer and used heavily in multi-threaded testing. You can use this class to simulate truly concurrent behavior i.e. trying to access something at the same time once every thread is ready. Worth noting is that CountDownLatch starts with a fixed number of counts which cannot be changed later, though this restriction is re-mediated in Java 7 by introducing a similar but flexible concurrency utility called Phaser.

java.lang.ClassNotFoundException: org.Springframework.Web.Context.ContextLoaderListener [Solution]

Problem : You are getting java.lang.ClassNotFoundException : org.Springframework.Web.
Context.ContextLoaderListener in your Spring-based Java Web application.
Cause : This error comes when you are using Spring MVC framework in your Java Web application and configured org.springframework.web.context.ContextLoaderListener as a listener in your deployment descriptor also known as web.xml, but the JAR which contains this class is not available in web application's CLASSPATH. This is a very important class in Spring MVC framework, as it is used to load your spring configuration files e.g. applicatoin-Context.xml and others, defined in the context-param element of web.xml of your Java spring web application, as shown below :


20 Java ArrayList Interview Questions Answers

In this article, I am going to share some of the good Java Interview questions based upon ArrayList class. I have hardly seen a Java interview without any question from ArrayList, and why not its one of the most popular collection class and every Java developer use it on their day to day work. Another reason for asking a question related to ArrayList is that you can ask a wide variety of question to really check breadth and depth of candidate's knowledge. To give you some idea about ArrayList, it's a collection class which implements List interface. It's an alternative to array data structure whose size you cannot change once created. ArrayList is a dynamic array, which can grow and resize itself. By implementing List interface it also got some properties e.g. ordering, ArrayList keeps the element in the order they are inserted and it also provides constant time search operation if you know the index of element e.g. get(index) is O(1) operation. This makes an ArrayList ideal choice when you are looking to retrieve values based upon the index.

How to reverse words in String Java? [Solution]

In this Java Coding tutorial, you will learn how to reverse words in String. It's also one of the popular coding questions, so you will also learn how to take a requirement, how to fill gaps in the requirement by asking the right question. A String is nothing but a sentence, which may contain multiple works, or just contain a single word or it may be empty. Your program must produce a String contains the word in reverse order , for example if given input is "Java is Great" then your program should return "Great is Java".  Now, if you are a good programmer then you should have some right questions for the programmer. Never assume you know everything, even if its looks a simple problem. Always remember "Devil is in detail". Also asking a question not only fill the gaps in requirement but also help you to make an impression.

How to Fix java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver [Solved]

Scenario : Your Java program, either standalone or Java web application is trying to connect to Oracle database using type 4 JDBC thin driver "oracle.jdbc.driver.oracledriver", JVM is not able to find this class at runtime. This JAR comes in ojdbc6.jar or ojdbc6_g.jar which is most probably not available in classpath.

Cause : When you connect to Oracle database from Java program, your program loads the implementation of Driver interface provided by the database vendor using class.forName() method, which throws ClassNotFoundException when driver class is not found in classpath. In case of Oracle the driver implementation is oracle.jdbc.driver.oracledriver and "java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver" error indicate that this class is  not available in classpath. Since this class is bundled into ojdbc6.jar, its usually the case of this JAR not present in Classpath

How to convert ByteBuffer to String in Java

You can easily convert ByteBuffer to String  in Java if you know how to convert byte array to String. Why? because it's very easy to convert ByteBuffer to a byte array and vice versa. All you need to do is call the ByteBuffer.array() method, it will return you the byte array used by java.nio.ByteBuffer class, later you can easily create String from that byte array. Though always remember to provide correct character encoding while converting byte array to String. For example, if you know that ByteBuffer is filled with bytes encoded in UTF-8 then you must use the same encoding while creating String from that byte array. String class provides an overloaded constructor which accepts character encoding along with byte array.  You can use the snippet shared in this example to do the job. ByteBuffer is one of the very useful class in java.nio package which is used to read data from channels and write data into channel directly.

java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject [Solved]

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlObject error means that your Java program needed a class called org.apache.xmlbeans.XmlObject but JVM is not able to find that in your application's CLASSPATH. You can see the actual cause of this error is "java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject". The most probable reason for this error could be a missing JAR file. In order to solve this error, you need to first find out which JAR file this class belongs. If you look at the error message it's clearly saying that it's from xmlbeans package, it means this class belongs to XMLBeans library.

How to use bitwise Operator in Java? Power of two example

In this Java Programming tutorial you will learn how to check if number is Power of two using bitwise operator. Main purpose or this program is to teach you how to use bit-wise operators like  bitwise AND (&)  in Java. A number is said to be power of two if all its prime factors are 2, but in binary world things works little differently. If you have read hacker's delight book then you know that there are several technique to check if a number is power of two or not, one of them is performing bit-wise AND operation between number and number -1, if result is zero then number is power of two. Just remember, here we are doing binary subtraction and not decimal one. In bitwise operator, each bit is used in evaluation for example if you use bitwise AND then each bit of both operand will go through AND operation and result will contain 1 only if both bits are one otherwise zero. I will explain how exactly this program work, but let's first see the program itself.

What is fail safe and fail fast Iterator in Java?

Java Collections supports two types of Iterator, fail safe and fail fast. The main distinction between a fail-fast and fail-safe Iterator is whether or not the underlying collection can be modified while its begin iterated. If you have used Collection like ArrayList then you know that when you iterate over them, no other thread should modify the collection. If Iterator detects any structural change after iteration has begun e.g adding or removing a new element then it throws ConcurrentModificationException,  this is known as fail-fast behavior and these iterators are called fail-fast iterator because they fail as soon as they detect any modification . Though it's not necessary that iterator will throw this exception when multiple threads modified it simultaneously. it can happen even with the single thread when you try to remove elements  by using ArrayList's remove() method instead of Iterator's remove method, as discussed in my earlier post, 2 ways to remove objects from ArrayList.

HelloWorld Program in Java - Example and Explanation

When I first started with Java programming, the fist program I wrote was HelloWorld in Java. That time I just copied it from a text book we were referring, I didn't know anything about it. It took me a lot of time to understand everything about HelloWorld in Java and how it works. From that time, I made it a rule to start with writing HelloWorld program in any new programming language I learn and try to understand every single element of it in as much detail as possible, but,  to be frank, its not that easy. When you write say HelloWorld in Java,  you are not capable enough to understand everything about it, and I found it better that instead of learning everything in one go, you should give yourself some time to let the knowledge you learned sink in. It's even better if you write HelloWorld program multiple times without looking at  the book. I have found that doing it repeatedly helps you to understand it better.

How to convert String to double in Java with Example

There are three ways to convert a String to double value in Java, Double.parseDouble() method, Double.valueOf() method and by using new Double() constructor and then storing resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time. Out of all these methods, the core method is parseDouble() which is specially designed to parse a String containing floating point value into the Double object. Rest of the methods e.g. valueOf() and constructor uses parseDouble() internally. This method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

Difference between synchronized ArrayList and CopyOnWriteArrayList in Java?

Though both synchronized ArrayList and CopyOnWriteArrayList provides you thread-safety and you can use both of them when your list is shared between multiple threads, there is a subtle difference between them, Synchronized ArrayList is a synchronized collection while CopyOnWriteArrayList is a concurrent collection. What does this mean? It means is that CopyOnWriteArrayList is designed keeping concurrency in mind and it is more scalable than synchronized ArrayList if the list is primarily used for reading. You know that ArrayList is not synchronized, so you cannot directly use it in a multi-threaded environment where you list is accessed and modified by multiple threads. In order to use ArrayList in such environment, you need to first get a synchronized list by calling Collections.synchronizedList().