5 Examples of substring() in Java


How to split String by comma in Java - Example Tutorial

In the earlier article, I have shown you how to split String by regular expression and now, you will learn how to split String by comma. Since CSV is a popular format of exporting data, you often need to split a comma separated String to create an array of individual Strings. Similar to the earlier example, you can use the split() method to accomplish this task. Just pass a "," instead of "\\s+" the regular expression to remove whitespaces, as the regular expression. The split method will return an array of String, which you can further convert to a list of String. If your String contains a leading or trailing white space, make sure you trim the String before calling the split() method. Also, remember that this method will throw PatternSyntaxException if the regular expression's syntax is invalid. Lat but not the least this version of the split method is only available from Java 1.4 onwards.

How to Run a JAR file from Command Prompt - Windows and UNIX

So you got a JAR file which contains your favorite Java game and you are wondering how to run Java program from JAR  file? Or you may be simply trying your hand after running Java program from the command prompt and Eclipse IDE. Anyway, it's good to know How to execute Java program from JAR file, as JAR file is a most popular way of shipping Java programs. JAR file usually contains all source and resource in the form of class files, images, sound files etc. In order to run Java program from JAR file, it must be an executable JAR file i.e. it manifest file inside META-INF folder must contain a Main-class entry like Main-Class: Hello, which specify the name of Java class which contains standard main method in Java. Without Main-class entry, you can not run a JAR file in Java and if you try to run such jar file using jar command you will get the error "Failed to load Main-Class manifest attribute from HelloWorld.jar". If you are not very much familiar with JAR file and don't know How to create an executable JAR, See this step by step tutorial on How to create executable JAR in Java. In this tutorial, we will only focus on running Java program from an executable JAR file.

Difference between NoClassDefFoundError vs ClassNotFoundExcepiton in Java

Both NoClassDefFoundError and ClassNotFoundException are dangerous errors which come when JVM or ClassLoader not able to locate class during the class loading process. Since different ClassLoader loads classes from a different location, sometimes this issue may be caused because of incorrect CLASSPATH as well i.e. some JAR files from lib are missing or from the old version. Though look quite similar there is a subtle difference between NoClassDefFoundError and ClassNotFoundException, NoClassDefFoundError indicates that class was present during the time of compilation but not available when you run Java program, sometimes error on static initializer block can also result in NoClassDefFoundError.

A Practical Example of Enum in Java

Enum is a useful feature of Java and the best way to represent fixed number of things e.g. a number of the planet in the solar system, the number of state order can be or simply a number of days in a week. Java Enum is different than their predecessor on other languages like C and C++, where the enum is just a wrapper around integer constant. Enum in Java is a full blown type like class and interface, they can have constructor (though only private constructors are permitted for Enum), they can override methods, they can have member variables, they can even declare methods, can implement interfaces and have specialized high performance Map and Set implementation in form of EnumMap and EnumSet.

How to Convert a List to a Set in Java with Example

How to convert a List to Set in Java
Many times we need to convert one collection to another e.g. converting a List to a Set. It'an also an easy way to copy contents from one collection to other in Java like from List to Set or Set to List. Thanks to Collection framework in Java, copying collection from one to other is extremely easy. Since every Collection class implements Collection interface which defines addAll() method, which can be used to create a collection from contents of another collection. In this Java tutorial, we will see an example of how to copy contents from List to Set in Java as part of copying data from one collection to other in Java. This is an actually nice way to convert List to Set in Java. You can use this technique to convert any List implementation to Set in Java.

What is Polymorphism in Java? Overriding or Overloading?

Polymorphism vs Overloading vs Overriding

Top 5 Java Main method Interview Questions with Answers

The main() method in Java is starting point of any standalone core Java application. JVM starts executing Java program from main method and the thread which executes main is called main thread in Java. The main method is also an important topic in Java interviews for 2 to 3 years experienced developer. In this Java article, we will a couple of questions related to the main method in Java. Apart from Why main is static in Java, I see following questions keep coming related to the main method:
  1. Can we overload the main method in Java? Which main method JVM will call?
  2. Can we override the main method in Java?
  3. Can we make main final in Java?
  4. Can we make main synchronized in Java?
  5. How to call a nonstatic method from main in Java?

Simplest way to impelment Singleton pattern in Java - Example

Singleton Pattern in Java

What is default Serialization in Java? Serializable and Externalizable Interface

What is Serialization in Java
Serialization in Java is a process to persist any Java Object's state into File System or convert them into byte stream to transfer over the network to other JVM or program. Serialization in Java is done by JVM by employing default Serialization process which persists all of Object's state except transient variable and a static variable. How Serialization works in Java  is another popular Java Serialization interview question, well It's easy to make any Java class Serializable, the class needs to implements interface and JVM will automatically serialize its instance when passed over to using writeObject(). Serializable interface is also called marker interface or tag interface because it does not contain any method or behavior and just used to tag a class, by seeing a class implementing Serializable JVM knows that it needs to serialize an instance of this class.

Difference between ArrayList and HashMap in Java

Difference between ArrayList and HashMap in Java
One of the most critical difference between HashMap and ArrayList class is that former is the implementation of the hash table while later is a dynamic array which can resize itself. The HashMap and ArrayList are two of the most popular classes from Java Collection framework. Though both are used to store objects but they are completely different on their implementation, working and usage. The main difference between ArrayList and HashMap is that ArrayList is index based data-structure backed by an array while HashMap is map data structure which works on hashing to retrieve stored values. This is also one of the frequently asked Java Collection interview questions, which is often asked Java developers of 1 to 3 years of experience. Apart from this fundamental difference between ArrayList and HashMap, there are many other differences, which we will see in this Java tutorial. But before that let's see some similarity between ArrayList and HashMap in Java.

6 Difference between include directive and include action in JSP

Difference between include directive and include action
Even though both include directive and include action allows you to include response of one JSP into another, they are quite different from each other e.g. include directive is processed at translation time and used to include the static resources e.g. HTML files, images and CSS etc, while the <jsp:include> action is processed at request time and used to include more dynamic resources e.g. JSP or Servlet. What is the difference between include directive and include action is also one of the most popular JSP interview questions, mostly asked either at telephonic round or first few round of Java web developer interviews? Let's see a couple of more difference between these two to answer this question in more detail. Btw, if you are new in JSP and just learning and preparing for interviews at the same time, then you should also look at Head First Servlet and JSP, one of the best books to learn and prepare for Servlet JSP interviews and certification at the same time.

4 ways to convert int value to String in Java? Examples

You can use String.valueOf() or Integer.toString() method to convert an int value to String object in Java. Remember, String is not just a char array but a full feature object in Java. The standard way to convert one object to String in Java is just calling the toString() method, but since here we need to convert primitive int to String, I prefer to use String.valueOf(int) method. It reads better because we are converting an int to String and not an Integer to String. There is a difference between them, int is a primitive value while Integer is a wrapper object in Java. BTW, there is one more way to convert an int value to String in Java, the easiest one, String concatenation. Even though Java doesn't support operator overloading, + operator behaves differently with integer and String operands. If one of the argument to this binary operator is String then it performs String concatenation, otherwise, it does addition. So you can convert an int value e.g. 10 to a String value "10" by just doing "" + 10.

Exception in thread "main" java.lang.IllegalStateException during Iterator.remove()

I was writing a sample program to demonstate how to remove elments from list while iterating over it by using Iterator.remove() mehtod. Unfortunately I was getting following error, right at the place where I was calling the Iterator.remove() method :

Exception in thread "main" java.lang.IllegalStateException
at java.util.ArrayList$Itr.remove(Unknown Source)
at dto.IteratorRemoveTest.main(

I was puzzled, why I am getting this error because I was using Iterator's remove() method and not the ArrayList's remove() method, which causes ConcurrentModificationException in Java.

7 differences between extends Thread and implements Runnable in Java

Java provides multithreading to parallelize execution of tasks (code) and you need threads to run multiple things in parallel e.g. download a file in the background and show the progress bar at front-end. There are two ways to create a Thread in Java, first by extending java.lang.Thread class and second by implementing the java.lang.Runnable interface. Since interviewer loves comparison based questions, what is the  difference between extending thread and implementing Runnable is also a popular Java thread question. In this article, I'll tell you how to answer this question by explaining the difference between extending the Thread class and implementing the Runnable interface, and which one is the better way to create threads In Java. Both approaches have their pros and cons and there is a situation when extending Thread is logical but in most cases implementing Runnable is the better option. Let's see the difference between extends Thread and implements Runnable in Java.

How to initialize HashMap with values in Java? One liner

There is often a situation where you would like to create a HashMap with some pre-defined mapping, but unfortunately, Java doesn't provide map literals like Groovy or Scala to create the map with values in the same line. If you remember, we have faced the same issue with other Collection classes as well e.g. ArrayList, Vector or LinkedList. But ArrayList is lucky because you can still use the Arrays.asList() method to create and initialize the ArrayList in just one line as shown here. But, how do you initialize the HashMap with values in Java? There is no such method like Arrays.asMap() or Collections.asMap(), and this is not just the question about HashMap but also about Hashtable, LinkedHashMap and ConcurrentHashMap. Well, there is an idiom called double brace initialization, which you can use to initialize the HashMap at the time of declaration. I'll show you how to use that double brace initialization to create HashMap with values in this article with a simple example.

10 difference between Struts and Struts2 framework in Java


Java Program to print prime numbers from 1 to 100

In this article, I'll share you a simple problem about writing a Java program to print prime numbers up to a given number e.g. say prime numbers from 1 to 100. It's one of the most common coding exercises for programmers learning in Java, as it gives you an opportunity to learn more about essential operator in Java Programming. The key here is that you cannot use a library function which can simply your job, you need to devise the algorithm for checking prime number by yourself. One of the most popular algorithms for generating prime is Sieve of Eratosthenes,  which we have discussed earlier, but in this post, we will take a simpler approach. We'll first write a function to check whether a number is prime or not and then we loop through first 100 numbers i.e. from 1 to 100 and print only those which passed the prime test. Btw, if you are looking for some serious programming coding question for the interview, then you can also take a look at Cracking the coding interview, which contains more than 150 coding question with solutions.

Difference between save(), saveOrUpdate() and persist() in Hibernate Session

Session interface in Hibernate provides a couple of methods to move an object from new or transient state to persistent state e.g. save(), saveOrUpdate() and persist() are used to store an object into the database, but there are some significant differences between them. The method does an INSERT to store the object into the database and it also return the identifier generated by the database. On the other hand, saveOrUpdate() can be used to reattach a detached object in Hibernate Session i.e. it can do INSERT or UPDATE depending upon whether object exists in database or not. The third method, persist() is similar to i.e. it is used to move a transient object to the persistent state by storing it into the database but it doesn't return the database identifier. This was the basic difference between save() vs saveOrUpdate() vs persist() method and suggest when to use which method. It is also one of the frequently asked Hibernate interview questions on Java Web developer job interviews. Knowing this detail help you to do well on your interview. Btw, if you have not read already then you must read Java Persistence with Hibernate, best book to learn these kinds of subtle details about Hibernate.