HTML

Best way to Convert Integer to String in Java with Example

Integer to String conversion in Java
There are many ways to convert an Integer to String in Java e.g. by using Integer.toString(int) or by using String.valueOf(int), or by using new Integer(int).toString(), or by using String.format() method, or by using DecimalFormat, String concatenation, or by using StringBuilder and StringBuffer etc. Some of them we have already seen on my earlier posts e.g. how to convert int to String and converting double to String. Even though those posts gives you tricks to convert primitive int to String and primitive double to String, you can still use those tricks to convert a wrapper class object e.g. Integer or Double to String in Java. Both are good ways, but out of those which is the best way to convert an Integer to String in Java?  You will find out in this article.

Java- Exception in thread "main" java.lang.NoClassDefFoundError Cause and Solution

NoClassDefFoundError in Java
The Exception in thread "main" java.lang.NoClassDefFoundError is a common error in Java which occurs if a ClassLoader is not able to find a particular class in the classpath while trying to load it. The Exception in thread "main" suggests that this error has occurred in the main thread, the thread which is responsible for running Java application. This error can occur to any thread but if it happens in main thread then your program will crash. As per Javadoc, NoClassDefFoundError can be thrown during linking or loading of the class file. It's denoted by java.lang.NoClassDefFoundError and comes when that particular class is present during compile time but somehow not available during runtime. This could be due to missing JAR file, any permission issue, or incorrect classpath on runtime, depending upon your environment.

How to create a ZIP File in Java? ZipEntry and ZipOutputStream Compression Example

Since compressing and archiving old log file is an essential housekeeping job in any Java application environment, a Java programmer should know how to compress files in .zip format and then how to read them programmatically if required. The JDK provides full support to create and read ZIP files in Java. There is a separate package java.util.zip to hold all classes related zipping and unzipping files and streams. In this series of article, you will learn how to use those classes e.g. ZipFile, ZipEntry, ZipInputStream, and ZipOutputStream etc. This is the second article about how to work with compressed archives in Java e.g. .zip files. In the last article, I have shown you how to read ZIP archives in Java and today, I'll teach you how to compress files in the ZIP file format by yourself using a Java program. You will compress a bunch of text file to create a .zip file by using JDK's ZIP file support classes.

Java Enum FAQ - What Every Java Developer should know about Enumeration type

Java Enum was one of the best features added on JDK 1.5 Tiger release along with Generics, Autoboxing, and varargs. Enum in Java represents fixed number of well-known things e.g. number of days in Week, the number of months in the calendar year etc. Unlike C and C++ Enum in Java are much powerful and they are not an integer constant, Instead, Enum is a Type like class or interface which provides compile time type safety. In this Java Enum tutorial, we will see a couple of important points about Java Enum which help to understand Enum better and get most out of it. I have written in the style of FAQ i.e. frequently asked questions, this will help you to learn more about Java Enum's capability and features e.g. whether Enum can extend class or implement methods or not? When you can override methods inside enum? whether you can compare Enum using equals() or == in Java? etc

Java ArrayList remove() and removeAll() - Example Tutorial

In this Java ArrayList tutorial, you will learn how to remove elements from ArrayList in Java e.g. you can remove String from ArrayList of String or Integer from ArrayList of Integers. There are actually two methods to remove an existing element from ArrayList, first by using the remove(int index) method, which removes elements with given index, remember index starts with zero in ArrayList. So a call to remove(2) in an ArrayList of {"one", "two", "three"} will remove 3rd element which is "three". The second method to remove element is remove(Object obj), which removes given object from ArrayList. For example, a call to remove("two") will remove the second element from ArrayList. Though you should remember to use Iterator or ListIterator remove() method to delete elements while iterating, using ArrayList's remove methods, in that case, will throw ConcurrentModificationException in Java.

7 Examples of String.format() and printf() in Java - Formatting Text and String in Java

You can format String in Java either by using String.format() method or by using System.printf() method, both uses TextFormat class to format String input internally. Both of these methods are inspired from C-Style printf() method and formatting instruction are very similar to C e.g. %s for String, %d for numeric, %f for floating point value and %n for new lines etc, but it is not exactly same as C. Some customization have been made to accommodate some Java language features. Java's String formatting is also more strict than C's, for example, if a conversion is incompatible with a flag then Java throws an Exception ( java.util.IllegalFormatConversionException), while in C, incompatible flags are silently ignored.

How to convert Timestamp to Date in Java -JDBC Example Tutorial

In the last article, I have shown you how to convert Date to Timestamp in Java and today we'll learn about converting timestamp value from database to Date in Java. As you remember, the JDBC API uses separate Date, Time and Timestamp class to confirm DATE, TIME and DATETIME data type from the database, but most of the Java object oriented code is written in java.util.Date. This means you need to know how to convert the timestamp to date and vice-versa. You can do by using the getTime() method, which return the number of millisecond from Epoch value. This can be used to create both Timestamp and java.util.Date, hence it acts as a bridge between Date class from java.util package and Date, Time and Timestamp class from the java.sql package. Like Date, Timestamp also contains both date and time value, so you won't see empty or zero time we saw previously while converting SQL Date to java.util.Date.

How to transpose a matrix in Java? Example Tutorial

Hello guys, continuing the tradition of this week, where I have mostly published articles about coding exercises for Java beginners, today also I am going to share an interesting coding problem, many of you have solved in your college or school days. Yes, it's about writing a Java program to transpose a matrix. In the last couple of tutorials, we have learned to how to add and subtract two matrices in Java (see here) and how to multiply two matrices in Java (see here). In this tutorial, I'll show you how to transpose a matrix in Java. The transpose of a matrix is a new matrix whose rows are the columns of the original. This means when you transpose a matrix the columns of the new matrix becomes the rows of the original matrix and vice-versa. In short, to transpose a matrix, just swap the rows and columns of the matrix. For example, if you have a matrix with 2 rows and 3 columns then transpose of that matrix will contain 3 rows and two columns.

How to Add and Subtract Two Matrices in Java

This is the second program in the series of matrices related programming exercises in Java. In the last program, you have learned matrix multiplication and in this program, you will learn how to perform addition and subtraction of two matrices in Java. We'll create methods to calculate both sum and difference of two matrices in Java program. In Mathematics, a matrix is a rectangular array with two dimensions known as rows and columns. In Java, your can use a two-dimensional array to represent a matrix because it also has two dimensions rows and columns. Since a 2D array is nothing but an array of the array in Java, the length of the outer array is equal to the number of rows and length of sub-array is equal to the number of columns.

How to calculate sum and difference of two complex numbers in Java

From the last couple of articles, I am writing about coding exercises for beginners e.g. yesterday you learned how to write a program from matrix multiplication in Java (see here) and a couple of days back, you have learned recursive binary search algorithm. To continue that tradition today I am going to show you how to write a program for calculating sum and difference of two complex numbers in Java. If you remember the complex number from you maths classes, it has two part real and imaginary and to add a complex number we add their real and imaginary part separately, similar to subtract complex number we minus their real and imaginary part separately. For example, if first complex number is A + iB and the second complex number is X + iY then the addition of these two complex number will be equal to (A +X ) + i(B + Y).

How to Multiply Two Matrices in Java

I first learned about matrix in class 12th and I first wrote the program to multiply two matrices on my first semester of engineering, so, when I thought about this program, It brings a lot of memories from the past. It's actually a beginner exercise to develop coding logic, much like Fibonacci, prime, and palindrome check, but what make this program interesting is the use of the two-dimensional array to represent a matrix in Java.  Since matrix has both rows and columns, two-dimensional array just naturally fits into the requirement. Another important thing to solve this problem is to remember the rule of matrix multiplication in mathematics. If you don't remember the rule, just forget about how to solve this problem, unless you have access to Google. So, first, we'll refresh the rules of multiplication and then we'll look into coding aspect.

java.lang.OutOfMemoryError: unable to create new native thread - Cause and Solution

There are several types of OutOfMemoryError in Java e.g. OutOfMemoryError related to Java heap space and permgen space, and a new one coming in Java 8, Java.lang.OutOfMemoryError: MetaSpace. Each and every OutOfMemoryError has their own unique reason and corresponding unique solution. For example, java.langOutOfMemoryError: Java Heap Space comes when the application has exhausted all heap memory and tries to create an object which requires further memory allocation, that time JVM throws this error to tell the application that it's not possible to create any object. Similarly java.lang.OutOfMemoryError: PermGen Space comes when there is no more memory in permgen space and application tries to load more classes (as class metadata is stored in this area) or tries to create new String (because prior to Java 7 String pool has also existed on permgen space).

5 Difference between StringBuffer, StringBuilder and String in Java

Though all three classes StringBuffer, StringBuilder and String are used for representing text data in Java there are some significant differences between them. One of the most notable differences between StringBuilder, StringBuffer, and String in Java is that both StringBuffer and StrinBuilder are Mutable class but String is Immutable in Java. What this means is, you can add, remove or replace characters from StringBuffer and StringBuilder object but any change on String object e.g. converting uppercase to lowercase or appending a new character using String concatenation will always result in a new String object. Another key difference between them is that both StringBuffer and String are thread-safe but StringBuilder is not thread-safe in Java. String achieves its thread-safety from Immutability but StringBuffer achieves it via synchronization, which is also the main difference between the StringBuffer and StringBuilder in Java.

JDBC - How to solve java.sql.BatchUpdateException: String or binary data would be truncated.

Recently I was working in Java application which uses Microsoft SQL Server at its backend. The architecture of Java application was old i.e. even though there was heavy database communication back and forth there was no ORM used e.g. no Hibernate, JPA, or Apache iBatis. The Java application was using old DAO design pattern, where the DB related classes which are responsible for loading and storing data from database was calling stored procedure to do their Job. These stored procedure takes data from Java application and insert into SQL Server tables. One day, one of my collegue called me to troubleshoot "java.sql.BatchUpdateException: String or binary data would be truncated", which it's application was throwing and he has no clue whatsoever that what is wrong with the data he is getting from other system and trying to store.

How to calculate average of all numbers of array in Java

In the last article, I teach you how to calculate the sum of all numbers in a given array and in this article, we'll go one more step. This time, you need to write a program to calculate the average of all numbers from a given array, for example, you will be passed salaries of Java developers in different states in the USA and you need to calculate the average salary of Java developer in the USA. The example of average salaries of Java developer is more interesting because everybody wants to know how much Java developers make, isn't it? Anyway, coming back to the requirement of the program, The array will contain integers, which can be both positive and negative, so you must handle them. Your program should also be robust e.g. it should not break if you pass empty array or null. In these case either you can throw IllegalArgumentException  as returning any other number will be ambiguous.

How to calculate sum of array elements in Java

In today's coding problem, we'll see how to write a program to calculate the sum of array elements in Java. You need to write a method which will accept an integer array and it should return total sum of all the elements. The array could contain both positive and negative numbers but only decimal numbers are allowed. The array can also be null or empty so make sure your solution handle those as well. In the case of a null or empty array, your program can throw IllegalArgumentException. The empty array means, an array whose length is zero or there is no element inside it. Well, that's enough for the requirement of this simple coding problem. The solution is really simple, just loop through the array and keep adding elements into sum until you process all the elements.

10 Reasons of java.lang.NumberFormatException in Java - Solution

The NumberFormatException is one of the most common errors in Java application along with NullPointerException. This error comes when you try to convert a String into numeric data types e.g. int, float, double, long, short, char or byte. The data type conversion methods like Integer.parseInt(), Float.parseFloat(), Double.parseDoulbe(), and Long.parseLong() throws NumberFormatException to signal that input String is not valid numeric value. Even though the root cause is always something which cannot be converted into a number, there are many reasons and input due to which NumberFormatException occurs in Java application. Most of the time I have faced this error while converting a String to int or Integer in Java, but there are other scenarios as well when this error occurs. In this article, I am sharing 10 of the most common reasons of java.lang.NumberFormatException in Java programs.

How to calculate area of triangle in Java - Program

Writing a Java program to calculate the area of a triangle is one of the basic programming exercises to develop coding sense on beginner programmers. Like many mathematical conceptual programs e.g. square root, factorial, or prime number this also serves a good exercise for beginners. Now, if you remember in maths you might have seen two main ways to calculate the area of a triangle, using vertices and using base and height. In this program, I have created two methods to calculate the area of a triangle using both ways. In the first method area(Point a, Point b, Point c)  we expect coordinates of three vertices of triangle and then we calculate area of triangle using the formula (Ax(By -Cy) + Bx(Cy -Ay) + Cx(Ay - By))/2, while in second method, area(int base, int height) we expect value of base and height and then we calculate are of triangle using formula (base * height) / 2.

3 ways to convert String to JSON object in Java?

It's very common nowadays to receive JSON String from a Java web service instead of XML, but unfortunately, JDK doesn't yet support conversion between JSON String to JSON object. Keeping JSON as String always is not a good option because you cannot operate on it easily, you need to convert it into JSON object before you do anything else e.g. retrieve any field or set different values. Fortunately, there are many open-source libraries which allows you to create JSON object from JSON formatted String e.g. Gson from Google, Jackson, and json-simple. In this tutorial, you will learn how to use these 3 main libraries to do this conversion with step by step examples.

3 Ways to Reverse an Array in Java - Coding Interview Question

One of the common coding questions is, how do you reverse an array in Java? Well, there are multiple ways to solve this problem. You can reverse array by writing your own function, which loops through the array and swaps elements until the array is sorted. That's actually should you be your first approach on interviews. Later you can impress the interviewer by a couple of other tricks, which is specific to Java development world. For example, you can reverse an array by converting array to ArrayList and then use this code to reverse the ArrayList. You can also use Apache Commons ArrayUtils.reverse() method to reverse any array in Java. This method is overloaded to reverse byte, short, long, int, float, double and String array. You can use any of the method depending upon your array type.

OOP Concept Tutorial in Java - Object Oriented Programming

I have written several OOP (Object Oriented Programming) concepts tutorials in past and I was thinking to bring them together so that anyone who wants to learn OOP basics can benefit from them easily. In this article, I will share you my collection of OOP tutorials and OOP concepts interview questions, which will not only help you to understand four pillars of Object Oriented programming e.g. Abstraction, Encapsulation, Inheritance, and Polymorphism but also powerful design techniques of Aggregation, Association and Composition, along with SOLID design principles, which are key to write flexible, extensible and object-oriented software. Java is also a great language to start with object-oriented programming, though it's not a pure object-oriented language it is the best one we have got so far. You cannot write code outside Class, which standardize the code organization.

When to use PUT or POST in RESTful Web Service

One of the most common confusion among web developers is the choice of PUT or POST HTTP method for creating or updating a resource while developing RESTful Web Services. Since both can be used to submit data, you can use either POST or PUT to create or update a resource. Many web developers want to use PUT for creating a resource on the server because it's idempotent. No matter, how many times you call the PUT, the state of the resource will not jeopardize. Since the possibility of re-submission is real on a slow network, using PUT to create resource makes it easy, as you don't need to worry about user clicking the submit button multiple times. But, the key point to remember is that when you use PUT to create a resource, you need to provide the id e.g.

SQL - 5 Best Books to Learn and Master SQL and Database design

The SQL (Structured Query Language) is one of the most important skills of a programmer. I would rate this skill similar to UNIX if you are a professional programmer because it doesn't matter whether you are Java, C++, or a .NET developer, you are bound to write SQL queries. Since a database is an integral part of any modern Java or Web application, Interviewer always preferred candidates with good SQL skills. Now, the big question comes, how a programmer can learn SQL? Does just knowing how to query a table is enough? If you know insert, update, delete, and select then are you a competent SQL programmer? What about indexes, query plans, triggers, views, stored procedures and other advanced SQL concepts? What about writing complex queries involving joins, subqueries, derived tables etc? Well, all those are very important to be a competent full stack developer.

3 ways to solve Eclipse - main class not found error

Like many Java programmers who get "Error: Could not find or load main class Main" while running Java program in Eclipse, I was also getting the same problem recently. The "Error: Could not find or load main class" was rendered me puzzled even after my 10+ years of experience with Java errors and exceptions. Whenever I run my Java application either by Run configurations or right click and run as Java program, I get an annoying popup complaining about "could not find or load the main class, the program will exit". I checked, the project was compiling fine, I can see the .class file for the main class in the bin directory of Eclipse, and I can even see the project and output folder added on the classpath of Run configuration, but still I am getting the "could not find main class, program will exit error".

10 Example of jQuery Selectors for Web Developers

I am primarily a Java developer but I have done a lot of work with Java web application including Servlet, JSP, and JavaScript on the client side. It was difficult for me to perform client side validation using JavaScript but ever since I come to know about jQuery, I simply love to do more validation and other stuff on the client side. The jQuery gives you immense power to do things with HTML pages and half of that power comes from its CSS-like selector engine, which allows you to select any element or group of elements from HTML page and then do things with them e.g. changes their style or behavior. For example, you can grab the divs and hide them, you can grab the buttons and make them clickable and so on. In order to learn jQuery, you need to learn its selector engine and in this tutorial, I am going to share you 10 good examples of different jQuery selectors e.g. ID selector to select single HTML element, the class selector to select group of an element and * wildcard to select all elements. Since jQuery supports many types of a selector, some of them I didn't even know, it's good to know as much as possible about them.

3 ways to count words in Java String

You can count words in Java String by using the split() method of String. A word is nothing but a non-space character in String, which is separated by one or multiple spaces. By using regular expression to find spaces and split on them will give you an array of all words in given String. This was the easy way to solve this problem as shown here, but if you have been asked to write a program to count a number of words in given String in Java without using any of String utility methods like String.split() or StringTokenizer then it's a little bit challenging for a beginner programmer. It's actually one of the common Java coding questions and I have seen it a couple of times with Java developer interviews of 2 to 4 years of experience. The interviewer put additional constraints like split() is not allowed, you can only use basic methods like charAt(), length(), and substring() along with loop, operators, and other basic programming tools.

Base64 Encoding and Decoding Example in Java 8 and before

Though, there are a couple of ways to Base64 encode a String in Java e.g. by using Java 6's javax.xml.bind.DatatypeConverter#printBase64Binary(byte[]) or by using Apache Commons Codec's Base64.encodeBase64(byte[) and Base64.decodeBase64(byte[])as shown here, or the infamous Sun's internal base64 encoder and decoder, sun.misc.BASE64Encoder().encode() and sun.misc.BASE64Decoder().decode(), there was no standard way in JDK API itself. That was one of the few missing item (another one is about joining string) which is addressed in Java 8. The JDK 8 API contains a Base64 class in java.util package which supports both encoding and decoding text in Base64. You can use Base64.Encoder to encode a byte array or String and Base64.Decoder to decode a base64 encoded byte array or String in Java 8.

5 Difference between Iterator and ListIterator in Java?

The Iterator is the standard way to traverse a collection in Java. You can use Iterator to traverse a List, Set, Map, Stack, Queue or any Collection, but you might not know that there is another way to traverse over List in Java? Yes, it's called the ListIterator. There are many differences between Iterator and ListIterator in Java, but the most significant of them is that Iterator only allows you to traverse in one direction i.e. forward, you have just got a next() method to get the next element, there is no previous() method to get the previous element. On the other hand, ListIterator allows you to traverse the list in both directions i.e. forward and backward. It has got both next() and previous() method to access the next and previous element from List.

Top 5 Apache Maven Free Ebooks for Java Developers

If you are working in Java for a couple of years you surely know about Maven, the most popular tool to build Java application. Recently I had shared 10 Maven Plugins Java developer should know and I receive a lot of good feedback about how useful those plugins and Maven, in general, is for Java developers. This motivated me to write more stuff about Apache Maven and then I thought about sharing some of the free ebooks Java developers can use to learn Maven. Sonatype, the company behind Nexus open source repository manager and creators of Apache Maven project provides a couple of good free ebooks to learn Maven and Nexus repository. Unlike other free ebooks which are mostly outdated, these Maven free eBooks are most accurate, up-to-date and can be used as reference material, particularly Maven: The Complete Reference.

Difference between include() and forward() methods of RequestDispatcher in Servlert

What is the difference between include and forward methods of RequestDispatcher interface is one of the frequently asked Servlet questions from Java EE interviews and we'll see how you can answer this question on your interview. You get the RequestDispatcher reference either from ServletContext or ServletRequest interface and even though both include() and forward() method allow a Servlet to interact with another servlet, main difference between include() and forward is that include() method is used to load the contents of the specified resource (could be a Servlet, JSP, or static resource e.g. HTML files) directly into the Servlet's response, as if it is part of the calling Servlet. On the other hand, forward() method is used for server side redirection, where an HTTP request for one servlet is routed to another resource (Servlet, JSP file or HTML file) for processing.

Difference between IdentityHashMap, WeakHashMap and EnumMap in Java

Apart from popular implementation like HashMap and LinkedHashMap, java.util.Map also has some specialized implementation classes e.g. IdentifyHashMap which uses == instead of equals() method for comparing keys, WeakHashMap which uses WeakReference to wrap the key object and a key/value mapping is removed when the key is no longer referenced from elsewhere, and EnumMap where keys are Enum constants. Many Java developer doesn't know about these special Map implementation classes and failed to take advantage of improved performance and feature offered by them. Their knowledge is also important from core Java interview perspective because Java interviewer put a huge focus on JDK API, particularly Java Collection framework and Java Concurrency framework which includes concurrent collections classes.

How to get current TimeStamp value in Java

Do you know that Java developer Google for even simplest of things? Yes, that's true and I can say it because even I do that :-). The current timestamp value is one of them. In UNIX you can just use the date command to get the current date and time but how do you get that in your Java program? Well, you can get the current timestamp in Java by using Date and Timestamp class of JDK. Note, there is "s" instead of "S" in Timestamp. Since Date in Java contains both date and time, it can be used as Timestamp value as well but when you print Date, it shows time in the local timezone. If you need just the timestamp, then you need to convert the java.util.Date to java.sql.Timestamp. You can convert a Date to Timestamp by using the getTime() method which returns the number of millisecond from the Epoch.

Difference between TCP and UDP in Java

What is the difference between TCP and UDP is a popular networking question from Java interviews? Though TCP or UDP is Java independent concept and very likely to be asked in other programming language interviews as well, many programmers not really understand them clearly. They sure have heard them because TCP and UDP are two of the most important transport protocol of internet, but when it comes to listing down the difference between them, they fail to mention key differences in terms of ordering, guaranteed delivery, speed, and usage. The biggest benefit of TCP/IP protocol is that it provides guaranteed to deliver of messages and in the order client sent them, that's very important when dealing with important messages e.g. order, trade, and booking messages. You cannot afford to lose them, neither you can process then out-of-sequence. The UDP protocol, on the other hand, provides the much-needed speed and can be used to implement a multicast network. In this article, I'll tell you the difference between TCP and UDP protocol from Java interview perspective.

3 ways to Copy a File From One Directory to Another in Java

Even though Java is considered one of the best feature-rich programming language, until Java 7, It didn't have any method to copy a file from one directory to another directory. It did have the java.io.File class, which provides a method to check if a file exists or not and methods for several other file operations but it lacks support for copying file from one folder to another. It was easy to write your own routine to copy a file using FileInputStream or FileChannel, most developers prefer to use Apache Commons IO library; which is not a bad idea at all. Even Joshua Bloch (author of several Java classes in JDK, including Java Collection Framework) advise using libraries instead of reinventing wheels in must read Effective Java book. The Apache Commons IO library provides a class called FileUtils, which contains several file utility methods including one for copying file from one directory to another.

Difference between early (static) binding vs late (dynamic) binding in Java

In order to understand the difference between static and dynamic binding in Java, it's important to first learn what is binding? Binding means the link between reference and actual code e.g. when you refer a variable it's bonded to the code where it is defined, similarly when you call a method, it's linked to the code where a method is defined. There are two types of method binding in Java, static binding and dynamic binding. When a method is called in Java it's bonded to the actual code either at compile time or runtime, when the program is actually started and objects are created. As the name suggest, static binding is more of static nature hence it occurs at compile time i.e. your code knows which method to call once you compiled your Java source file into a class file. Since it happens early in program's life cycle it is also known as early binding in Java.

How to fix "illegal start of expression" error in Java

The "illegal start of expression" error is a compile time error when the compiler finds an inappropriate statement in the code. The java compiler, javac, compiles your source code from top to bottom, left to right and when it sees something inappropriate at the start of an expression, it throws "illegal start of expression" error. The most common reason of this is a missing semi-colon. You might know that every statement in Java ends with a semicolon, but if you forget one, you won't get an error that there is a missing semi-colon at the end of statement because the compiler doesn't know the end. When compiler checks the next statement it sees illegal start because an earlier statement was not terminated. The bad part is that you can get tens of "illegal start of expression" error by just omitting a single semi-colon or missing braces, as shown in the following example.

How to fix "class, interface, or enum expected" error in Java

If you have ever written Java programs using Notepad or inside DOS editor, then you know that how a single curly brace can blow your program and throw 100s of error during compilation. I was one of those lucky people who started their programming on DOS editor, the blue window editor which allow you to write Java program. I didn't know about PATH, CLASSPATH, JDK, JVM, or JRE at that point. It's our lab computer where everything is supposed to work as much our instructor wants. Since we don't have the internet at that point of time, we either wait for the instructor to come and rescue us and we surprise how he solve the error by just putting one curly brace and all errors mysteriously go away.  Today, I am going to tell you about one such error,  "class, interface, or enum expected".   This is another compile time error in Java which arises due to curly braces. Typically this error occurs when there is an additional curly brace at the end of the program.

How to read a text file as String in Java

There was no easy way to read a text file as String in Java until JDK 7, which released NIO 2. This API now provides a couple of utility methods which you can use to read entire file as String e.g. Files.readAllBytes() returns a byte array of the entire text file. You can convert that byte array to String to have a whole text file as String inside your Java program. If you need all lines of files as List of String e.g. into an ArrayList, you can use Files.readAllLines() method. This return a List of String, where each String represents a single line of the file. Prior to these API changes, I used to use the BufferedReader and StringBuilder to read the entire text file as String. You iterate through the file, reading one line at a time using readLine() method and appending them into a StringBuilder until you reach the end of the file. You can still use this method if you are running on Java SE 6 or lower version.

Difference between a class and an interface in Java

It is one of the frequently asked Java questions from beginners which struggles to get the concept behind an interface. The main difference between a class and an interface lies in their usage and capabilities. An interface is the purest form of abstraction available in Java where you just define the API or contract e.g. you define run() method on the Runnable interface without worrying about how something will run, that is left to the implementor which will use a class to define how exactly to run. So an interface gives you method name but how the behavior of that method is come from the class which implements it. That's your general difference between an interface and class in Java and applicable to all object oriented programming language, not just Java. Even though this question is not exactly the difference between abstract class and interface, it's somewhat related to it because an abstract class is nothing but a class with some abstract method. The points I have discussed there, also applicable here in terms of rules of Java programming related to class and interface.

Difference between HashMap vs IdentityHashMap in Java?

The IdentityHashMap is one of the lesser known Map implementation from JDK. Unlike general purposes Map implementations like HashMap and LinkedHashMap, it is very special and it's internal working is quite different than HashMap. The main difference between IdentityHashMap and HashMap in Java is that former uses equality operator (==) instead of equals() method to compare keys. Which means you need the same key object to retrieve the value from IdentityHashMap, you cannot retrieve values by using another key which is logically equal to previous key. Another important difference between HashMap and IdentityHashMap is that IdentityHashMap doesn't use hashCode() method instead it uses System.identityHashCode() method. This is a significant difference because now you can use mutable objects as key in Map whose hash code are likely to change when the mapping is stored inside IdentityHashMap.

How to read a text file in Java - BufferedReader Example

There are multiple ways to read a file in Java e.g. you can use a Scanner as we have seen in the last example, or you can use the BufferedReader class. The advantage of using a BufferedReader to read a text file is speed. It allows faster reading because of internal buffering provided by BufferedReader. Other Reader classes e.g. FileReader access the file or disk everytime you call the read() method but BufferedReader keeps 8KB worth of data in its internal buffer which you can read it without accessing file multiple times. It's loaded when you access the file first time for a subsequent read. The BufferedReader class is also a good example of Decorator design pattern because it decorates existing readers e.g. FileReader to provide buffering, remember, the reading from file functionality still comes from the FileReader class.

How to replace an element of ArrayList in Java?

You can use the set() method of java.util.ArrayList class to replace an existing element of ArrayList in Java. The set(int index, E element) method takes two parameters, first is the index of an element you want to replace and second is the new value you want to insert. You can use this method as long as your ArrayList is not immutable e.g. not created using Collections.unmodifiableList(), in such case the set() method throws java.lang.UnsupportedOperationExcepiton. Though, you can also use the set() method with the List returned by Arrays.asList() method as oppose to add() and remove() which is not supported there. You just need to be careful with the index of elements. For example, if you want to replace the first element then you need to call set(0, newValue) because similar to an array, ArrayList index is also zero based.

Common reasons of java.lang.ArrayIndexOutOfBoundsException in Java

The ArrayIndexOutOfBoundsException, also known as java.lang.ArrayIndexOutOfBoundsExcepiton is one of the most common errors in Java program. It occurs when Java program tries to access an invalid index e.g. an index which is not positive or greater than the length of an array. For example, if you have an array of String e.g. String[] name = {"abc"} then trying to access name[1] will give java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 error because index 1 is invalid here. Why? because index in Java array starts with zero rather than 1, hence in an array of just one element the only valid index is index zero.  This was one of the most common scenarios which cause several million of ArrayIndexOutOfBoundsException daily. Sometimes it just a plain programming error but sometimes if an array is populated outside and if there is an error on feed than also you get java.lang.ArrayIndexOutOfBoundsException in Java.

Top 5 OCPJP7 books for 1Z0-804 and 1Z0-805 Exam - Java SE 7 II Certification

You may know that from Java SE 7 onwards, you need to pass two exams to become a certified Java developer e.g. OCAJP and OCPJP. The first one is an associate level exam and it's rather easy to pass, but the second one OCPJP is a professional level exam and it's much harder than OCAJP. If you are giving the Oracle Java certification then you should know that you need to pass OCAJP before taking OCPJP exam. This is also the second part of an article about books to prepare Java SE 7 certifications. In the first part, I have shared best books for OCAJP7 and in this part, I am going to share best books for the OCPJP7 exam. You might know that there are two professional level exam, 1Z0-804, and 1Z0-805, the first one is known as OCPJP7 while the second one is known as an upgrade to Java SE 7 certification, which you can give to become certified Java SE 7 developer if you already passed SCJP 5 or OCJP 6 exam. The books recommended in this article is applicable to both OCJPJP7 (1Z0-804) and upgrade to Java SE 7 (1Z0-805) exams.

How to join two ArrayList in Java - Example

You can use the addAll() method from java.util.Collection interface to join two ArrayLists in Java. Since ArrayList implements List interface which actually extends the Collection interface, this method is available to all List implementation including ArrayList e.g. Vector, LinkedList. The Collection.addAll(Collection src) method takes a collection and adds all elements from it to the collection which calls this method e.g. target.addAll(source). After this call, the target will have all elements from both source and target ArrayList, which is like joining two ArrayList in Java. The second ArrayList will remain as it is but the first ArrayList on which you have added elements will have more elements. Its size will be equal to the sum of the size of first and second ArrayList.

How to read a text file into ArrayList in Java

Prior to Java 7, reading a text file into an ArrayList involves lot of boiler plate coding, as you need to read the file line by line and insert each line into an ArrayList, but from Java 7 onward, you can use the utility method Files.readAllLines() to read all lines of a text file into a List. This method return a List of String which contains all lines of files. Later you can convert this List to ArrayList, LinkedList, or whatever list you want to. Btw, this the fourth article in the series of reading a text file in Java. In the earlier parts, you have learned how to read a file using Scanner and BufferedReader(1). Then, reading the whole file as String (2) and finally reading a text file into array (3). This program is not very different from those in terms of fundamentals. We are still going to use read() method for Java 6 solution and will read all text until this method return -1 which signals the end of file.

3 Best books to prepare OCAJP 7 (1Z0- 803) Exam - Java SE 7 Certification

Even though the latest OCAJP exam is OCAJP8, the OCAJP7 still the most popular one, at least from the email I receive, I can say that more readers ask for OCAJP7 recommendations and preparation tips than OCAJP8. I have always said the three golden rules of success in OCAJP exam is selecting a good book, writing programs, and doing mock exams e.g. Whizlabs or Enthuware practice tests. In this article, you will find some good OCAJP7 books to deal with the first part. For those, who are new to the structure of Java SE 7 certification, it's now divided into two parts, the OCAJP and OCPJP. The OCAJP stands for Oracle Certified Associate Java Programmer and it's an associate level exam. The OCPJP stands for Oracle Certified Professional Java Programmer and it's a professional level exam. The difference between them is both on exam topic and toughness. The OCPJP is tougher and advanced than OCAJP. Topics like JDBC and Concurrency are included only in OCPJP, you don't need to read them in order to clear the OCAJP exam.

What is the difference between byte and char in Java?

The byte and char are two numeric data types in Java and both can represent integral numbers in a range but there are very different from each other. The main difference between a byte and char data type is that byte is used to store raw binary data while other is used to store characters or text data. You can store character literal into a char variable e.g. char a = 'a'; A character literal is enclosed in single quotes. In terms of range, a byte variable can hold any value from -128 to 127 but a char variable can hold any value between 0 and 255. Another difference between byte and char in Java is that the size of the byte variable is 8 bit while the size of the char variable is 16 bit. One more difference between char and byte is that byte can represent negative values as well but char can only represent positive values as its range is from -128 to 127. In other words, a byte is a signed data type where the first byte represent the sign of number i.e. 0 for positive and 1 for a negative number, but char data type is unsigned. Let's see some more differences between byte and char in Java.

How to fix "variable might not have been initialized" error in Java

This error occurs when you are trying to use a local variable without initializing it. You won't get this error if you use a uninitialized class or instance variable because they are initialized with their default value e.g. Reference types are initialized with null and integer types are initialized with zero, but if you try to use an uninitialized local variable in Java, you will get this error. This is because Java has the rule to initialize the local variable before accessing or using them and this is checked at compile time. If compiler believes that a local variable might not have been initialized before the next statement which is using it, you get this error. You will not get this error if you just declare the local variable but will not use it.

How to find length/size of ArrayList in Java? Example

You can use the size() method of java.util.ArrayList to find the length or size of ArrayList in Java. The size() method returns an integer equal to a number of elements present in the array list. It's different than the length of the array which is backing the ArrayList, that is called the capacity of ArrayList. When you create an object of ArrayList in Java without specifying a capacity, it is created with a default capacity which is 10. Since ArrayList is a growable array, it automatically resizes when the size (number of elements in array list) grows beyond a threshold. Also, when an ArrayList is first created it is called empty ArrayList and size() will return zero. If you add elements then size grows one by one. You can also remove all elements from ArrayList by using a clear() method which will then again make the ArrayList empty as shown in our examples.

How to remove all elements of ArrayList in Java - Example

There are two ways to remove all elements of an ArrayList in Java, either by using clear() or  by using the removeAll() method. Both methods are defined in the java.util.List and java.util.Collection interface, hence they are available not just to ArrayList but also to Vector or LinkedList etc. Both elements removes all objects from ArrayList but there is a subtle difference in how they do. The clear() method is straightforward, it traverse through the ArrayList and sets all indices to null, which means the ArrayList becomes empty and all elements become eligible to Garbage collection, provided there is no more references to them. The time taken by clear() method is in O(n), which means the bigger the arraylist the longer it will take to empty it.

3 Difference between Web Server vs Application vs Servlet Containers in Java JEE

In the Java EE, or J2EE or JEE world, there is a lot of confusion between terminology, which is quite evident that now we have three words (J2EE, Java EE, and JEE) to describe the same technology platform. You will see Java developers using the terms like Web Server, Application Server, and Web containers interchangeably but they are not exactly same. The main difference between a Web server and an application server is that web server is meant to serve static pages e.g. HTML and CSS, while Application Server is responsible for generating dynamic content by executing server-side code e.g. JSP, Servlet or EJB. One of the most popular web servers is Apache HTTPD which is often used in conjunction with Tomcat to host many Java web application. Now, tomcat is not exactly an application server, it's more of a servlet engine or web container or also known as servlet containers because it provides the runtime environment for Servlet and JSP but doesn't provide the services like EJB and distributed transaction which are a key feature of the application server in Java JEE world.

How to Add Elements of two Arrays in Java - Example

One of the common programming exercise on various Java course is addition and multiplication of two arrays. How do you add two integer arrays in Java? Can you add two String array? how about other data types etc? These are some of the interesting questions because Java doesn't support operator overloading. You cannot use the plus operator to add two arrays in Java e.g. if you have two int arrays  a1 and a2, doing a3 = a1 + a2 will give compile time error. The only way to add two arrays in Java is to iterate over them and add individual elements and store them into a new array. This is also not easy because the array can be of different length, so you need to make some rules and apply them to your method e.g. you can throw IllegalArgumentException if you get two arrays which are not of the same type and their length is different.

Difference between Daemon Thread vs User Thread in Java?

A thread is used to perform parallel execution  in Jaa e.g. while rendering screen your program is also downloading the data from the internet in the background. There are two types of threads in Java, user thread and daemon thread, both of which can use to implement parallel processing in Java depending upon priority and importance of the task. The main difference between a user thread and a daemon thread is that your Java program will not finish execution until one of the user thread is live. JVM will wait for all active user threads to finish their execution before it shutdown itself. On the other hand, a daemon thread doesn't get that preference, JVM will exit and close the Java program even if there is a daemon thread running in the background. They are treated as low priority threads in Java, that's why they are more suitable for non-critical background jobs. In this article, we will learn some key difference between user and daemon thread from Java multithreading and interview perspective.

How to count a number of words in given String in Java?

Can you write a method in Java which accepts a String argument and returns a number of words in it? A word is a sequence of one or more non-space character i.e. any character other than '' (empty String). This should be your method signature:

public int count(String word);

This method should return 1 if the input is "Java" and return 3 if the input is "Java, C++, Python". Similarly a call to wordCount("    ") should return 0.  This is one of the several String algorithmic questions you can expect in a programming job interview.  This is used to test the coding skills of the candidate and that's why it's very important to prepare for these questions anytime you go for an interview.

java.sql.SQLException: No suitable driver found for 'jdbc:mysql://localhost:3306/mysql [Solution]

This error comes when you are trying to connect to MySQL database from Java program using JDBC but either the JDBC driver for MySQL is not available in the classpath or it is not registered prior to calling the DriverManager.getConnection() method. In order to get the connection to the database, you must first register the driver using Class.forName() method. You should call this method with the correct the name of the JDBC driver "com.mysql.jdbc.Driver" and this will both load and register the driver with JDBC. The type 4 JDBC driver for MySQL is bundled into MySQL connector JAR e.g. mysql-connector-java-5.1.18-bin.jar depending upon which version of MySQL database you are connecting. Make sure this JAR is available in classpath before running your Java program, otherwise Class.forName() will not be able to find and load the class and throw java.lang.ClassNotFoundException: com.mysql.jdbc.Driver, another dreaded JDBC error, which we have seen in the earlier post.

Unsupported major.minor version 52.0 in Java + Eclipse + Linux [Solution]

The "unsupported major.minor version 52.0" error started to come after Java SE 8 release and the root cause of this error is trying to run a Java application compiled with JDK 8 into a JRE lower than Java SE 8 e.g. JRE 7 or JRE 6. This is very common because a developer has updated their compiler or IDE to Java SE 8 but many times their runtime is not upgraded to Java 8. If you remember, in Java you can run a class file compiled with a lower version say Java 6 to a higher version say JRE 8 because Java is backward compatible but vice-versa is not allowed. This make sense because Java SE 8 has features like lambda expressions, method reference, functional interface and new Date and Time API, which lower version JRE has no information. Depending upon where you getting this error e.g. Eclipse, NetBeans, IntelliJ IDEA or Android Studio, the solution could be different. All these IDEs has different settings for JRE but the bottom line is same, you need to configure these IDE to use JRE 8 to run the Java program compiled using Java 8.

4 ways of Session management in Servlet Java

Session tracking or Session management is an important feature of modern web applications which allows the server to remember it's clients. By keeping a session for each user, Server can serve the client better. It also helps in safety, security and personalization and must for certain kind of web applications e.g. e-commerce sites like Amazon or e-bay which stores item selected by the user for purchase in a shopping cart, even after the user is logged out. Since HTTP is a stateless protocol, there are no ways to know that two HTTP requests are related to each other i.e. they are coming from the same client or they are part of the same process. Session tracking is a mechanism that Servlets and Java Web application use to maintain state about a series of request from the same user across some period of time. By keeping a session, an e-commerce site can maintain add to card facility and also keep tracks of how you interact with the application. Since HTTP doesn't provide a default way to track Session, there are some non-standard ways to manage Sessions in Servlet JSP based application. Let's have a close look on them.

How to print Floyd's triangle in Java - Example Tutorial

In the last article, I have taught you how to print Pascal's triangle and in today's article I'll teach you how to print Floyd's triangle in Java program. Floyd's triangle is easier to print than Pascal's triangle because you don't need to take care of formatting the numbers as Floyd's triangle is a right angle triangle. It is named after American computer scientist Robert Floyd, who has also contributed Floyd–Warshall algorithm, which efficiently finds all shortest paths in a graph and Floyd's cycle-finding algorithm for detecting cycles in a sequence. If you remember, we use this algorithm to find the cycles in linked list. Coming back to Floyd's triangle, it is a right angle triangle which consists natural numbers starting from 1 in the first row. It then goes on with two numbers in second row, 3 numbers in 3rd row and so on. Along with other pattern based exercises and Pascal's triangle, Floyd's triangle is also a good programming exercise and often used in programming and training courses to teach how to program to beginners. It's one of the easier program but help you to build code sense and how to use basic programming constructs e.g. loop, operators and functions.

How to print Pascal Triangle in Java - Example Tutorial

Printing patterns with stars or numbers and triangles are some of the the common programming exercises. Earlier we have seen how to print pyramid pattern with stars and today you will learn how to print Pascal's triangle in Java. Sometime this problem is also asked as "write a program to print Pascal triangle without using array" or by just using for loop. Pascal’s triangle is a set of numbers arranged in the form of a triangle, similar to Floyd's triangle but their shape is different. Each number in the Pascal triangle row is the sum of the left number and right number of the previous row. If a number is missing in the above row,  it is assumed to be 0. The first row starts with number 1, that's why you will see that first two row of Pascal triangle just contain 1.

keySet() vs entrySet vs values() Example in Java Map

The java.util.Map interface provides three methods keySet(), entrySet() and values() to retrieve all keys, entries (a key-value pair), and values. Since these methods directly come from the Map interface, you can use it with any of the Map implementation class e.g. HashMap, TreeMap, LinkedHashMap, Hashtable, ConcurrentHashMap, and even with specialized Map implementations like EnumMap, WeakHashMapand IdentityHashMap. In order to become a good Java developer, it's important to understand and remember key classes Java API e.g. Java's Collection framework. In this article, we will not only learn the difference between keySet(), entrySet() and values() methods, but also learn how to use them in Java program by looking at a simple example.

Java Program to calculate Area of Circle

You can calculate the area of a circle in Java by just writing a class and a method. All you need to know is the formula to calculate the area of circle and trick to get input from the user in Java. If you know these two already than the calculating area of a circle is very easy. Since every program must have a class in Java, we need to create a class. I have created a class called Circle for our examples purpose. Now, since the execution of Java program starts from the main method, I have provided a public static void main() method in our program. This single method is enough to put all the code required for this program e.g. getting input from the user, calculating area and displaying area of a circle in the console. But, for better coding experience purpose, we'll just create a method to calculate the area of a circle.

Fibonacci Series in Java Using Recursion

Fibonacci series in Java
Write a Java program to print Fibonacci series up to a given number or create simple Java program to calculate Fibonacci number is common Java questions on fresher interview and homework. Fibonacci series is also a popular topic on various programming exercises in school and colleges. Fibonacci series is series of natural number where next number is equivalent to the sum of previous two number e.g. fn = fn-1 + fn-2. The first two numbers of Fibonacci series is always 1, 1. In this Java program example for Fibonacci series, we create a function to calculate Fibonacci number and then print those numbers on Java console. Another twist in this questions is that sometime interviewer asks to write a Java program for Fibonacci numbers using recursion, so it's better you prepare for both iterative and recursive version of Fibonacci number.

Difference between static and nonstatic member variables in Java

In the last article, I had explained about some key difference between static and nonstatic methods in Java, and in this part, I'll explain the difference between static and nonstatic member variables in Java. The concept of static remains same, that doesn't change with method or member variables but there are still some subtle details, which every Java programmer should know and understand. As with static methods, a static member variable belongs to a class and a non-static member variable belongs to an instance. This means, the value of a static variable will be same for all instances, but the value of a non-static variable will be different for different objects. That is also referred as the state of objects. The value of nonstatic member variable actually defines the state of objects.

10 points about wait(), notify() and notifyAll() in Java Thread?

If you ask me one concept in Java which is so obvious yet most misunderstood, I would say the wait(), notify() and notifyAll() methods. They are quite obvious because they are the one of the three methods of total 9 methods from java.lang.Object but if you ask when to use the wait(), notify() and notfiyAll() in Java, not many Java developer can answer with surety. The number will go down dramatically if you ask them to solve the producer-consumer problem using wait() and notify(). Many will use if block instead of while loop, many others will get confused on which object they should call wait() and notify()method? Some of them even succeed in creating livelock, deadlock, and other multithreading issues.

Difference between Static vs non Static method in Java

One of the key difference between a static and a non-static method is that static method belongs to a class while non-static method belongs to the instance. This means you can call a static method without creating any instance of the class by just using the name of the class e.g. Math.random() for creating random numbers in Java. Often utility methods which don't use the member variables of the class are declared static. On the other hand, you need an instance of the class to call a non-static method in Java. You cannot call it without creating an object because they are dependent upon the member variables which has different values for different instances.  One more important difference between the static and non-static method is that you cannot use a non-static member variable inside a static method, you cannot even call a non-static method from the static method, but the opposite is true e.g. you can call a static function from a non-static method in Java.

Double Checked Locking in Java and Why it was broken before JDK 5?

Double checked locking pattern is one of the interesting topics on Java Interviews. Earlier, it was asked to see if Java developer can write code using synchronized block or not and now it ask to gauge the candidate's understanding of concurrency, volatile and synchronization in Java. One of the simplest ways to write thread-safe Singleton was to make the getInstance() method synchronized but prior to JDK 1.6, a simple uncontented synchronization block was expensive and that lead many developers to write the getInstance() method of Singleton class using double-checked locking idiom. This was one of the clever idiom of that time which only uses synchronization when the Singleton object is created as seen in the following code and thus improves the performance of getInstance() method, which is used to retrieve the Singleton object.