5 Examples of substring() in Java

SubString in Java is a useful method from java.lang.String class, which is used to create smaller String from bigger ones. The way Substring works prior to Java 1.7 can create a subtle memory leak because both String and their substring shares same character array. Which means, if you have a big String of 200MB and created a substring of 2MB from that, that could prevent 200MB String from being garbage collected. I agree this doesn't look normal and indeed was a bug, but it was like that till Java 1.6 and it's various update. One reason, which I could think, why Java designer initially thought like that, maybe to save memory by sharing char array and to make, creating substring faster by just copying pointers, instead of data. Nevertheless, this was reported as bug and Oracle have fixed it, so no more substring memory leak issue in Java 7.

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.

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?

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.

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

What is the difference between Struts 1 and Struts 2 is one of the popular Struts interview questions from Java JEE interviews? If you have mentioned Struts in your CV then you can expect this question on the telephonic or face-to-face round of interview. Struts 1.x was a very popular MVC framework for Java web application on last decade, but when Spring MVC comes it lost a lot of its sheen. Spring framework's dependency injection and inversion of control feature, along with several other template based features makes it the de-facto framework for developing Java application. But, the demand of Struts was not completely gone, there are still a lot of enterprise application written in Struts which needs Java developer with knowledge of Struts to maintain and develop them, so it's one of the good skill to get a Java web developer job. Apache than comes with Struts 2, the new version of Struts which supports dependency injection and several other features. In this article, I'll show you some key difference between Struts 1 and Struts 2 from interview point of view, but if you are learning Struts 2 by yourself and looking for a good book than buy Struts 2 in Action, one of the best books to learn Struts 2.