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.

10 Free Java Programing Books for beginners - download, pdf and HTML

Every Java programmer loves free eBooks on Java, don't you? When I shared my collection of top 5 Java programming books, one of my reader asked me to share some free Java books as well. Doing a quick search on the internet, reveals lots of free books, resource, and tutorials to learn Java. I have chosen some of the good Java books, which are FREE, available for download or you can read it online in HTML or PDF format. These books are an excellent resource for any Java beginners, as well as an experienced programmer, and since they are free, it makes absolute sense to have a look on this before buying any other book in Java.  These free Java books cover a wide range of technology including core Java, J2EE, JSP, Servlets, XML and general programming concepts. Though books like Effective Java or Java Concurrency in Practice are not free, they are worth of every penny spent. I didn't find any good FREE Java books on concurrency and multithreading, which I really wanted to include. If you come across a genuine FREE multithreading books for Java programmer, then please let us know.

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.

Difference between List and ArrayList variable in Java?

Someone who is just starting with Java programming language often has doubt about how we are storing an ArrayList object in List variable, what is the difference between List and ArrayList? or why not just store the ArrayList object in ArrayList variable just like we do for String, int, and other data types. Well, the main difference between List and ArrayList is that List is an interface while ArrayList is a class. Most importantly, it implements the List interface, which also means that ArrayList is a subtype of List interface. In Java or any object oriented language, super type of variable can store an object of subtype. This is known as Polymorphism because any virtual method will be executed from subclass only, even though they were called from super type. This is the beginning, now let's see those two questions as well.

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
Someone asked me What are the difference between Polymorphism and Overriding in Java and the similar difference between Polymorphism and Overloading. Well, they are not two different things, Polymorphism is an object oriented or OOPS concept like Abstraction, Encapsulation or Inheritance which facilitate the use of the interface and allows Java program to take advantage of dynamic binding in Java. Polymorphism is also a way through which a Type can behave differently than expected based upon which kind of Object it is pointing. Overloading and overriding are two forms of Polymorphism available 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?

5 Main Method Interview Questions with Answers


Can we overload main in Java?
Yes you can overload the main method in Java, nothing wrong with this but Java will only call your specific main method, i.e. main method with the following signature:
public static void main(String[] args) or  public static void main(String args...) which is the main method as variable argument method and only supported post-Java 5 world.




Can we override main in Java?
No, you can not override the main method in Java, Why? because main is a static method and in Java static method is bonded during compile time and you can not override static method in Java. If you declare a method with same name and signature its called method hiding.


Can we make main final in Java?
Of course, you can make the main method final in Java. JVM has no issue with that. Unlike any final method, you can not override main in Java.



Can we make main synchronized in Java?
Yes, main can be synchronized in Java,  synchronized modifier is allowed in the main signature and you can make your main method synchronized in Java.


How to call a nonstatic method from main in Java?
This question applies not only to main but all static methods in Java. Since nonstatic methods can not be called from static context directly, you need to first create an Object as local variable and then you can call nonstatic method using that object, as shown in the following example:

Frequently asked question on main method in Java with answersimport java.util.Date;


/**
 * Java program to show how to call non static method from static method in Java
 *
 * @author http://java67.blogspot.com
 */

public class StaticTest {

    public static void main(String args[]) {
     
        // calling non static method from main in Java
        //printCurrentTime(); //compile time error - can not call non static method from main
     
        StaticTest test = new StaticTest();
        test.printCurrentTime();
     
    }
 
 
    public void printCurrentTime(){
       System.out.println(new Date());
    }
}

Output:
Tue Nov 06 19:07:54 IST 2012


Summary

  1. The main() method is a static method
  2. You can overload main() method in Java.
  3. You cannot override main() method in Java
  4. You can make the main method final in Java
  5. You can make the main method synchronized in Java.
  6. You cannot call a non-static method from main in Java. 

10 points about Main method in Java

So these were some of the frequently asked questions about the main method in Java. This does not only help to answer interview question but also to build your concept on the main method in Java.


Other Java Interview questions you may like

Simplest way to impelment Singleton pattern in Java - Example

Singleton Pattern in Java
Singleton pattern in Java is used to create a Singleton class which is accessed by single instance though out Java program life cycle.Singleton is one of the old but very useful design pattern and used in several core Java libraries including Java Development Kit (JDK); java.lang.Runtime is an example of Singleton pattern in Java. This class represent a single instance of Java environment running as JVM and provides several utility methods to query important details about runtime like a number of available processors, Java heap memory etc. Singletons are also very popular in Java interview and one of the frequently asked question. This article contains a great collection of interview question on Singleton pattern in Java and can be useful to enhance your knowledge on Singleton pattern.

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 java.io.Serializable interface and JVM will automatically serialize its instance when passed over to java.io.ObjectOutputStream 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.

How to Count number of 1s (Set Bits) in Given Bit Sequence in Java

Good morning folks, In today's article, we are going to discuss one of the frequently asked bit manipulation based interview question, how do you count the number of set bits in given bit sequence? It is also asked as how to count the number of 1s in given number? Both are the same question because 1 is also known as set bit.  For example if given input is 1000110010 than your program should return 4, as three are only four set bits in this bit sequence. There are many techniques to solve this problem. Best way to learn why a given algorithm works is to take a pencil and run though a few examples. The solution presented in this article, you might have seen this already in hackers delight, runs through a loop and clears the lowest set bit of number during each iteration. When no set bit is left (i.e. number==0) than the number of iterations is returned. That's your number of 1s or set bits in given bit sequence. Let's learn more about how this algorithm works.

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.

2 Ways to Remove Numbers from Integer Array in Java?

In the last article, I have showed you how to reverse an array in place in Java and now I have come back with another array based coding interview question. It's also one of the frequently asked coding questions, not as popular as the previous one but still has been asked lot of times. Let's see the problem statement first.

Problem: Given an array and a value, write a function to remove all instances of that value from the array in Java (in place) and return the new length, or simply print out the array before and after removing the number. The order of elements can be changed. It doesn't matter what you leave beyond the new length. For example, if the given array is {12, 122, 12, 13, 14, 23, 14}, and number to be removed is 12 then the result array should be {122, 13, 34, 23,14}, and the length of the new array is 5.

Java Program to reverse an array in place? Fastest Example

It's easy to reverse an array if you have the luxury to use another array, but how would you reverse an array if a temporary buffer is not allowed? This is one of the testing array interview questions, which often proved tricky for Java programmers. Well, you can also reverse an array in place without using an additional buffer. If you know how to access array elements and how to loop over an array in Java using traditional for loop, you can easily solve this problem without using additional space. All you need to do is loop over the array from start to the middle element and swap first element to the last, second element to the second last etc. Once you reach the middle element, your array is already sorted and that too without using any additional space. You can even use this algorithm to reverse a String in Java as well. After all, a String is backed by character array.

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(IteratorRemoveTest.java:25)

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.

10 Examples of forEach() method in Java 8

From Java 8 onward, you can iterate over a List or any Collection without using any loop in Java. The new Stream class provides a forEach() method, which can be used to loop over all or selected elements of list and map. forEach() method provides several advantage over traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of regular stream. Since you are operating on stream, it also allows you to filter and map elements. Once you are done with filtering and mapping, you can use forEach() to operate over them. You can even use method reference and lambda expression inside forEach() method, resulting in more clear and concise code. If you not started with Java 8 yet than you should make it one of your new year resolution for 2016. Coming years will see much more adoption of Java 8. If you are looking for a good book to learn Java 8, than you can use Java 8 in Action, one of the best book about lambda expression, stream and other functional aspect of Java 8. For now, let's see a couple of examples of forEach() in Java 8.

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 implement singly linked list in Java using Generics

Linked list is a popular data structure for writing programs and lots of questions from linked list is asked in various data structures and algorithmic interviews. Though Java provides a sound implementation of Doubly linked list as java.util.LinkedList, all these interview questions require you to code linked list in Java. If you are not comfortable to make a linked list, it would be really difficult to solve questions like reversing a linked list or finding middle element of linked list. Java 5 brought another twist of this kind of questions, now interview expects you to write a type-safe implementation of linked list using Generics. This raise difficulty level as writing parameterized class is not easy in Java, and it requires a good understanding of Generics fundamental.

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.

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 algorithm 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 Session.save() 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 Session.save() 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.