HTML

java.lang.IllegalStateException: getOutputStream() has already been called for this response

This error comes when you call include() or forward() method after calling  the getOutputStream() from ServletResponse object and writing into it.  This error is similar to java.lang.IllegalStateException: getWriter() has already been called for this response error, which we have seen in the earlier article.

This is the exception:
org.apache.jasper.JasperException: java.lang.IllegalStateException: getOutputStream() has already been called for this response
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:424)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
HelloServlet.doGet(HelloServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)

and here is the root cause :

6 Difference between forward() and sendRedirect() in Servlet - Java

Servlet in JEE platform provides two methods forward() and sendRedirect() to route an HTTP request to another Servlet for processing. Though, both are used for forwarding HTTP requests for further processing there are many differences between forward() and sendRedirect() method e.g. forward is performed internally by Servlet, but a redirection is a two-step process, where Servlet instruct the web browser (client) to go and fetch another URL, which is different from the original. That's why forward() is also known as a server-side redirect and sendRedirect() is known as the client-side redirect. Becuase of their usefulness, the difference between forward() and sendRedirect is also a frequently asked Servlet interview question. Let's see a couple of more differences to answer this question better.

Difference between yield and sleep in Java Thread

Sleep vs yield in Java
Sleep and yield are two methods which are used to get CPU back from Thread to Thread Scheduler in java but they are completely different than each other. The major difference between Sleep vs yield is that sleep is more reliable than yield and it's advised to use sleep(1) instead of yield to relinquish CPU in multi-threaded Java application to give an opportunity to other threads to execute. In this Java tutorial, we will what are differences between yield and sleep in Java. But before seeing difference between sleep and Yield let's see some similarities between yield and sleep in Java

Difference between HashMap and LinkedHashMap in Java

Difference between LinkedHashMap and HashMap in Java
HashMap and LinkedHashMap are two of the most common used Map implementation in Java. Main difference between HashMap and LinkedHashMap is that LinkedHashMap maintains insertion order of keys, order in which keys are inserted in to LinkedHashMap. On the other hand HashMap doesn't maintain any order or keys or values. In terms of Performance there is not much difference between HashMap and LinkedHashMap but yes LinkedHashMap has more memory foot print than HashMap to maintain doubly LinkedList which it uses to keep track of insertion order of keys. Some time you notice that HashMap also returns elements in order e.g. before Java 8 when you use Integer key and then iterate over Map, you would see it returning entries in a particular order, but those are not guaranteed. Any code which is dependent upon ordering provided by HashMap will likely to break in future release when those behavior changes.

Difference between TreeMap and TreeSet in Java

Difference between TreeSet and TreeMap in Java
Main Difference between TreeMap and TreeSet is that TreeMap is an implementation of Map interface while TreeSet is an implementation of Set interface. There are some similarities between both TreeMap and TreeSet and few differences as well. In this Java tutorial, we will first see similarities between TreeMap and TreeSet and than you will learn some differences between TreeMap and TreeSet in Java. Key point to remember about TreeMap and TreeSet is that they use compareTo() or compare() method to compare object, So if uses puts a String object in TreeSet of Integers, add() method will throw ClassCastException at runtime prior to Java 5, with Java 5 you can use Generics to avoid this happening by declaring TreeMap and TreeSet with parametrized version. If you want to master Java Collection framework by heart, you can see Java Generics and Collection book by Maurice Naftaline, one of the best work on Java Collections framework.

How to find even and odd number in Java - Program tutorial example

Even and Odd number check Java Example
There are many ways to find if a number is even or odd in Java but before moving into technical details on finding even and odd number in Java let's what is even and odd number in terms of Mathematics. Any number which is completely divisible by 2 is called even number while number which is not completely divisible by 2 is called odd number. If you think in terms of remainder than in the case of even number, the remainder is zero while in the case of odd number remainder will be 1. zero is considered as an even number in maths. We can use this property to find whether a number is even or odd in Java. Java has a remainder operator also called modules operation denoted by % which does exactly same. it returns remainder as a result of the division. here is a Java sample program of finding even and odd number using remainder and bitwise AND operator in Java.

Java Program to find Armstrong numbers with Example

Armstrong number Example in Java
How to check if a number is Armstrong number or not? or write a Java program to find Armstrong number? This is a common Java interview question asked on campus interviews and fresher level interviews. This is also a popular Java programming exercise on various school, colleges and computer courses to build programming logic among Students. An Armstrong number is a 3 digit number for which sum of cube of its digits is equal to the number itself. An example of Armstrong number is 153 as 153= 1+ 125+27 which is equal to 1^3+5^3+3^3. One more example of the Armstrong number is 371 because it is the sum of 27 + 343 + 1 which is equal to 3^3 + 7^3 + 1^3 . In this Java program example, we will see complete code example of Java program to check if any 3 digit number is Armstrong number or not. If you are going for Java interview, then be prepare for some follow-up questions e.g. finding prime numbers, or finding Armstrong number of more than 3 digits.

Difference between CountDownLatch and CyclicBarrier in Java Concurrency


Difference between CountDownLatch and CyclicBarrier in Java
Both CyclicBarrier and CountDownLatch are used to implement a scenario where one Thread waits for one or more Thread to complete there job before starts processing but there is one Difference between CountDownLatch and CyclicBarrier in Java which separates them apart and that is, you can not reuse same CountDownLatch instance once count reaches to zero and latch is open, on the other hand CyclicBarrier can be reused by resetting Barrier, Once barrier is broken.

Difference between ArrayList and HashSet in Java

ArrayList vs HashSet Java
Main difference between ArrayList and HashSet is that one is a List implementation while other is a Set implementation. It means all the differences between a List data structure and a Set data structure also applies to this pair. For example, List implementations are ordered, it store element in the order they were added, while Set implementation doesn't provide such guarantee. Similarly, since List provides Random access, you can access any element directly if you know the index, but Set doesn't provide such facility. You need to Iterate through whole collection to get access of any elements. We will see couple of more difference in this Java tutorial. By the way ArrayList and HashSet are two most common Collection class used in Java programming language and before discussing difference between ArrayList vs HashSet, let's see some similarities between them :

String to Enum in Java - Conversion Example

Creating Enum from String
You can create Enum from String by using Enum.valueOf() method. valueOf() is a static method which is added on every Enum class during compile time and it's implicitly available to all Enum along with values(), name() and cardinal() methods. In order to create Enum from String, String must be same as declared Enum otherwise, the code will throw "java.lang.IllegalArgumentException: No enum const class". the same technique can be used to convert String into Enum instance as well. This is the second part of Enum conversion tutorial, in the first part, we have seen how to convert Enum to String in Java. If you have not read that yet, check it out. Also from Java 7 onwards, Java started supporting String constants in switch cases, but you should always prefer Enum over both Integer and String constant because Enum provides type safety. The compiler will ensure that incorrect value is not supplied, but in the case of String and Integer, the compiler will check whether a variable is of the correct type, but it won't check values, which is why you should use Enum to define a well-known fixed number of things. 

Difference between List and Set in Java

List vs Set in Java
Main Difference between List and Set is that List is an ordered Collection while Set is an unordered collection. Java collection framework offers several collection classes for various needs but all collection can be divided into broadly three categories : List, Set, and Map. All List, Set, and Map are defined as interfaces and then you have several implementation like ArrayList and Vector are the popular implementation of List interface, while HashSet is a popular implementation of Set interface. In this java tutorial, we will mainly see What are differences between List and Set collection at the top level and How to choose when to use List in java and when to use Set in Java. I believe once you are able to understand the fundamental difference between List and Set you are most likely be well versed on when to use List and when to choose Set.

How to find GCD of two numbers in Java - Euclid's algorithm

How to find Greatest Common Divisor of two numbers in Java
Simple Java program to find GCD (Greatest common Divisor) or GCF  (Greatest Common Factor) or HCF (Highest common factor). The GCD of two numbers is the largest positive integer that divides both the numbers fully i.e. without any remainder. There are multiple methods to find GCD , GDF or HCF of two numbers but  Euclid's algorithm is very popular and easy to understand, of course, only if you understand how recursion works. Euclid's algorithm is an efficient way to find GCD of two numbers and it's pretty easy to implement using recursion in Java program. According to Euclid's method GCD of two numbers a, b is equal to GCD(b, a mod b) and GCD(a, 0) = a. The later case is the base case of our Java program to find GCD of two numbers using recursion. You can also calculate greatest common divisor in Java without using recursion but that would not be as easy as the recursive version, but still a good exercise from coding interviews point of view.

How Java achieves platform independence

Java is platform independent language How?
Java programming language provides platform independence, what does it mean ? It means same Java program can be run on any platform or operating system e.g. Windows, Linux or Solaris without any change. This is the great benefit for some one coming from platform dependent programming language like C or C++ whose code needs to be ported for every single platform because they use native libraries, which differ in every platform. Now question comes how Java achieve platform independence, what makes Java programs running on every platform without any change ? This is one of the most basis question Java programmer ask when they start learning Java programming language. If you read further you will come to know about class files, bytecode and Java virtual machine which together provides platform independence to Java. One of the simplest analogy I can associate with platform independence is the person taking red carpet with him and instead of walking on floor, he always walks on red carpet, no matter where he is walking. That red carpet is the JVM, your Java program runs on JVM rather on any particular platform or machine. 

Difference between yield and wait method in Java Thread

Yield vs wait in Java
Yield and wait method in Java, though both are related to Threads,  are completely different to each other. Main difference between wait and yield in Java is that wait() is used for flow control and inter thread communication while yield is used just to relinquish CPU to offer an opportunity to another thread for running. In this Java tutorial we will what are differences between wait and yield method in Java and when to use wait() and yield(). What is important for a Java programmer is not only understand difference between wait() and yield() method but also know implications using yield method. If your program is depends upon yield method for performance or correctness than its most likely not work perfectly on all platforms because of platform dependent nature of yield method which we will see in this Java article along with wait vs yield comparison.

How to convert Enum to String in Java with Example

Enum to String Conversion Example in Java
There are two ways to convert an Enum to String in Java, first by using name() method of Enum which is implicit method and available to all Enum and second by using toString() method. name() method of Enum returns exact same String which is used to declare a particular Enum instance like in WeekDays Enum if we have MONDAY as one Enum instance than the name() will return String "MONDAY". This method of conversion from Enum to String is useful if String representation of Enum is same as its String name but if you have different String representation then you can use toString() method. Since Enum in Java allows a programmer to override an inherited method and since Enum has access to all Object class method, you can easily override toString() method to provide a custom String implementation for an Enum instance which can further use to convert that Enum instance to String in Java.

How to Make Collection like ArrayList Read Only in Java?

Read only Collection in Java
You can create read-only Collection by using Collections.unmodifiableCollection() utility method. it returns a unmodifiable or read-only view of Collection in which you can not perform any operation which will change the collection like add() , remove() and set() either directly or while iterating using Iterator or ListIterator. It will throw UnsupportedOperationException whenever you try to modify the List. One of the common misconception around read only ArrayList is that, you can create read-only ArrayList by using Arrays.asList(String{[]), which is apparently not true as this method only return a fixed size list on which add() and remove() are not allowed by set() method is still allowed which can change the contents of ArrayList. Collections class also provide a different method to make List and Set read-only. In this Java tutorial, we will learn How to make any collection read only and How to create fixed size List as well.

Top 21 Java Inheritance Interview Questions and Answers

Last week I wrote about some good Java OOP concept questions and In this article, I am going to share some frequently asked Inheritance based Java Interview questions and answers. Inheritance is one of the most important Object oriented concepts along with Abstraction, Encapsulation, and Polymorphism. Since most popular languages are object oriented e.g. Java and C++, you will always find a couple of questions from OOP concepts, particularly from Polymorphism and Inheritance. It's expected from a Java developers to know about these OOP concepts and have an understanding of when to use them e.g. many times Composition is the better choice than Inheritance because of flexibility it offers but when it comes to leverage polymorphism of type, you have to use Inheritance. In Java inheritance is supported by language using extends and implements keyword.

How to get ArrayList from Stream in Java 8 - Collectors Example, Tutorial

You can use Collectors.toList(), toSet() and toMap() to get all elements of Stream into any Collection e.g. List, Set or Map, but if you want to get a particular collection e.g. ArrayList, then you need to use Collectors.toCollection(ArrayList::new) method. This method first creates an ArrayList using method reference and then adds all elements of Stream into the ArrayList. It's very useful if you have a long list of String and you want to create a smaller list containing only String starting with the letter "b" e.g. "Bluehost". All you need to do is first get the stream from List by calling stream() method, then call the filter() method to create a new Stream of filtered values and finally call the Collectors.toCollection(ArrayList::new) to collect those elements into an ArrayList. Let's see a couple of examples to understand the concept better.

How to connect Eclipse to Oracle database - Step by Step Guide

Though I prefer Toad or Oracle SQL Developer tool to connect Oracle database, sometimes it's useful to directly connect Eclipse to Oracle using JDBC using its Data Source Explorer view. This means you can view data, run SQL queries to the Oracle database right from your Eclipse window. This will save a lot of time wasted during switching between Toad and Eclipse or Oracle SQL Developer and Eclipse. Eclipse also allows you to view Execution plan in both text and Graphical mode, which you can use to troubleshoot performance of your SQL queries. In this article, I'll tell you steps to connect Eclipse to Oracle database. Since Eclipse uses Java to connect to Oracle database, it asks for JDBC driver information. Since connecting using thin Oracle JDBC driver is much easier, as you just need to drop a JAR file in the classpath, we will be using JDBC thin driver to connect Oracle from Eclipse. Depending upon your Oracle version e.g. Oracle 10g or Oracle 11g you need to download Oracle JDBC thin driver e.g. ojdbc14.jar file. Just download this JAR file and configure it on Eclipse IDE. Enter the username, password, and sid and you are ready to execute SQL query to Oracle database from Eclipse.

How to convert java.util.Date to java.sql.Timestamp in Java - JDBC Example

You can convert java.util.Date to java.sql.Timestamp by first taking the long millisecond value using the getTime() method of Date class and then pass that value to the constructor of Timestamp object. Yes, it's as simple as that. For better code reusability and maintenance, you can create a DateUtils or MappingUtils class to keep these kinds of utility or mapping functions. Now, the questions comes, why do you need to convert java.util.Date to java.sql.Timestamp? Well, If you are storing date values to database using JDBC, you need to convert a java.util.Date to its equivalent java.sql.Timestamp value. Even though both of them represent date + time value and can be stored in DATETIME SQL type in Microsoft SQl Server database or equivalent in other databases like Oracle or MySQL, there is no method in JDBC API which takes the java.util.Date object. Instead, you have got three separate methods to set DATE, TIME, and TIMESTAMP in the java.sql package.

Difference between FileReader vs FileInputStream in Java?

Even though both FileReader and FileInputStream are used to read data from a file in Java, they are quite a different. The main difference between the FileReader and FileInputStream is that one read data from character stream while other read data from a byte stream. The FileReader automatically converts the raw bytes into character by using platform's default character encoding. This means you should use this class if you are reading from a text file which has same character encoding as the default one. If you happen to read a text file encoded in different character encoding then you should use InputStreamReader with specified character encoding. An InputStreamReader is a bridge between byte stream and character stream and can take a FileInputStream as a source. Though, it's worth remembering that it caches the character encoding which means you cannot change the encoding scheme programmatically.

How to convert Date to LocalDateTime in Java 8 - Example Tutorial

The LocalDateTime class has introduced in Java 8 to represents both date and time value. It's local, so date and time is always in your local time zone. Since java.util.Date has been widely used everywhere in many Java applications, you will often find yourself converting java.util.Date to LocalDate, LocalTime and LocalDateTime classes of java.time package. Earlier I have shown you how to convert Date to LocalDate and today, I am going to teach you how to convert Date to LocalDateTime in Java 8. The approach is same. Since the equivalent class of java.util.Date in new Date and Time API is java.time.Instant, we first convert Date to Instance and then create LocalDateTime instance from that Instant using System's default timezone.

How to use flatMap() in Java 8 - Stream Example Tutorial

In order to understand the flatMap() method, you first need to understand the map() function of Java 8. The map() function is declared in  the java.util.stream.Stream class and uses to transform one Stream into another e.g. a stream of integer numbers into another stream of ints where each element is the square of the corresponding element in source stream. In the map() function, a function is applied to each element of Stream and return values are inserted into a new Stream. The key point to note here is that the function used by map() operation returns a single value. Now, if the map operation uses a function which instead of returning a single value returns a Stream of values e.g. prime factors of the number then you have a Stream of Stream of integers. The flatMap() method is used to flatten that stream into a Stream of integers. For example, suppose, you have a list of numbers e.g. [21, 23, 42] and we use getPrimeFactors() method along with the map() operation to transform this stream. The result would be [[3,7],[23],[2,3,7]]. If you want to flat this stream of a stream into a stream of values, you can use the flatMap() which will return [3,7,2,3,2,3,7].