HTML
Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.

How to Implement Thread-Safe Bounded Buffer in Java? Example

This is one of the common coding problems for Java developers which the interviewer asks to check both their coding skills as well to test their concurrency skills. A BoundedBuffer is a common data structure used in concurrent Java applications to pass data between threads. For example, you can use Bounded Buffer to implement the Producer-Consumer pattern in Java. Producer thread can put items for consumers to process and can wait if Buffer is full. This pattern allows Consumers to process items already placed in queue or buffer.  

How to Create Java Project with Maven in Eclipse - Step by Step Guide

If you are not using Maven for managing dependency and creating a build for your Java project, then you are definitely missing something. Being an ardent fan of ANT, I started with Maven quite late, but once I started, I haven't looked back. Maven makes it so easy to add new open-source JAR files, building and testing your project that you wouldn't look back. By the way, like all the things starting is difficult. I spent countless hours will creating my first Java project using Maven and Eclipse, but those were days with older Eclipse IDE

Difference between Type 1, 2, 3 and 4 JDBC Driver in Java? Example

One of the oldest Java interview questions is what is the difference between different types of JDBC drivers e.g. what is the difference between type 1, type 2, type 3, or type 4 drivers? Sometimes also asked as to how do you choose between different JDBC drivers? When to use type 3 over type 4 driver etc. It's 2015 now and I doubt anyone is using JDBC driver other than type 4 for connecting to the database, but let's see how to answer this question when you face it during the interview. The difference between different types of JDBC drivers comes from the fact how they work, which is basically driven by two factors, portability, and performance. 

Difference between ISNULL() and COALESCE() function in SQL? Example

Even though both ISNULL() and COALESCE() function provides alternate values to NULL in T-SQL and Microsoft SQL Server e.g. replacing NULL values with empty String, there are some key differences between them, which is often the topic of SQL Server interview. In this article, you will not only learn the answer to this question but also learn how to use COALESCE and ISNULL function properly. One of the main differences between them is that  COALESCE() is a standard SQL function but ISNULL() is Microsoft SQL Server-specific, which means it's not guaranteed to be supported by other database vendors like Oracle, MySQL, or PostgreSQL.

3 ways to create random numbers in a range in Java - Examples

Many times you need to generate random numbers, particular integers in a range but unfortunately, JDK doesn't provide a simple method like nextIntegerBetween(int minInclusive, int maxExclusive), because of that many Java programmers, particularly beginners struggle to generate random numbers between a range, like random integers between 1 to 6 if you are creating a game of dice, or a random number between 1 to 52 if you are creating a game of playing cards, and you need to choose a random card, or most commonly random numbers between 1 to 10 and 1 to 100. Then, the question comes, how to solve this problem? How to generate random int values between a range? Well, you need to do a little bit of work.

Difference between OCAJP7, OCAJP8, and OCAJP11 Certification - 1Z0-803 vs 1Z0-808 vs 1Z0-815

One of the frequently asked questions asked by most of the OCAJP certification candidates is, what are the differences between OCAJP 8 and OCAJP 7? And, after Java 11 certification release, what is the difference between OCAJP 11 (1Z0-815) and OCAJP 8 (1Z0-808) Which one Java developers should go for? OCAJP7 or OCAJP8, or OCAJP 11? The obvious answer to this question is the latest Java version of the exam, I mean OCAJP 11. Since it's already more than a couple of months since Java 12 is out but there is no OCAJP 9 certification, the OCAJP 8 should be the exam, Java developers should pursue this year and beyond. 

10 Example of jQuery Selectors for Beginners

I am primarily a Java developer but I have done a lot of work with Java web applications 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 the 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. 

5 ways to redirect a web page using JavaScript and jQuery

When an HTTP request for one page automatically goes to another page then it is called redirection. The redirection of a web page is used for different reasons like redirecting to a different domain e.g. when you move your website from one URL to another URL or redirecting to a more recent version of a page you are looking at it. There are many ways to redirect a web page and different web technologies provide different ways like Java provides sendRedirect() and forward() method for redirection. 

Difference between table scan, index scan, and index seek in SQL Server Database? Example

Hello guys, a good understanding of how the index works and how to use them to improve your SQL query performance is very important while working in a database and SQL and that's why you will find many questions based upon indexes on Programming Job interviews. One of such frequently asked SQL questions is the real difference between table scan, index scan, and index seek? which one is faster and why? How does the database chooses which scan or seek to use? and How you can optimize the performance of your SQL SELECT queries by using this knowledge. In general, there are only two ways in which your query engine retrieves the data, using a table scan or by using an index.

7 Reasons of NOT using SELECT * in a SQL Query? Best Practices

I have read many articles on the internet where people suggest that using SELECT * in SQL queries is a bad practice and you should always avoid that, but they never care to explain why? Some of them will say you should always use an explicit list of columns in your SQL query, which is a good suggestion and one of the SQL best practices I teach to junior programmers, but many of them don't explain the reason behind it. 

Difference between OCAJP and OCPJP Certification Exams for Java Programmers

Earlier when Sun Microsystems was in charge of Java, the popular Java certifications were called "Sun Certified Java Programmer" or "SCJP" and that time there was just one exam, you need to pass to become a certified Java Developer, but when Oracle took over Sun Microsystems on 2010, the SCJP goes away and OCAJP and OCPJP born. Since Oracle already has its certifications for database administrations like OCA, which stands for Oracle certified associates, and OCP, which stands for Oracle Certified Professional, it introduces new Java certifications to match their existing hierarchy. They are known as OCAJP and OCPJP in the Java world.

How to find swap space and usage in Solaris? Swap Command Example

Swap space in Solaris or any UNIX host is a vital disk space that is used for the swapping process from physical memory (RAM)  to disk. Virtual memory allows a process to run even if physical memory gets full by using swap space (which is located on your hard disk) to swap out memory pages that are not currently in use. This is a very important concept which every programmer and Linux user should know. It is even more important if you are working in IT support or as a system admin because if swap space is full then swapping will fail and no new process will be able to start. 

How to backup and load Cron Jobs from a File in Linux and UNIX? Crontab Command Example

Hello guys, If you have been using Linux for some time then you might know about cron jobs. They are the scheduler that can be used to automatically start processes in a Linux box. I have worked on many projects which used cron jobs to start the Java process and environment daily or weekly basis. They are similar to Autosys when it comes to scheduling jobs but cron is a Linux command as opposed to Autosys which is a separate application altogether. In Linux, the crontab command is used for scheduling and automating jobs or processes. You can also use it for loading cron jobs from a file, listing existing cron entries, and editing them. It manages the cron table that is used by the cron daemon in Linux to execute the cron jobs.

How to send Logging Messages to SysLog using Log4j2 SysLogAppender in Linux ? Java Example

Sometimes you may want to route your log messages to Syslog in UNIX-based environment like Linux. Since logger allows multiple appenders, you can print the same log messages to a log file, console, and route it to Syslog at the same time. In order to send log messages to Syslog using log4j2, you need to make some changes in your log4j2.xml file. This change is to include the Syslog appender and configure that, once you do that you also need to enable TCP or UDP reception by editing rsyslog.conf file. For faster transmission you can choose UDP protocol and configure a port number on which your Syslog is listening, In our example, Syslog is listening on port 618. Let's see the complete step-by-step guide to configure Syslog logging in log4j logger.

The Ultimate Guide of String in Java - Examples

someone might question that why do we need another article about string in Java, haven't we had enough about the string is already written? Yes, I agree there are a lot of articles related to Java string covering topics like how to use Java String, an example of Java string, and almost everything you can do with string in Java. But, I wanted to document my experience of using String in Java and some nasty and little-known things I discovered about the Java String class, which may not be obvious to many Java developers.

How to combine two Map in Java? Example Tutorial

You can combine two maps in Java by using the putAll() method of java.util.Map interface. This method copies all the mappings from one Map to another, like, if you call it like first.putAll(second), then all mappings from the second Map will be copied into the first Map. This means if the first map contains 5 elements and the second map contains 10 elements or mapping, then the combined map will contain 15 or fewer mappings. In the case of duplicate keys, the value is overridden or updated from the second map.

How to use Stream and Lambda Expressions for Clean Code in Java? Examples

Hello guys, writing Clean Code in Java has always been my passion, more so after reading the Clean Code book by legendary author Uncle Bob Martin. I always look for ways to make my concise yet more readable but sometimes Java's verbose nature comes into the way. Thankfully after the introduction of powerful features like Lambda expression and Stream API, writing clean code in Java has become much easier. Streams enable the user to combine commands in some sort of pipeline just like we combine Linux commands using pipe and result in high-quality code which describes what you are doing instead of how to do things.

How to Convert a List of String to Comma Separated String (CSV) in Java 8? Example

Before Java 8, it was not straightforward to convert a list of String to a comma-separated String. You have to loop through the collection or list and join them manually using String concatenation, which can take up more than 4 lines of code. Of course, you could encapsulate that into your own utility method and you should but JDK didn't provide anything useful for such a common operation. Btw, things have changed. From Java 8 onwards you can do this easily. JDK 8 has provided a utility class called StringJoiner as well as added a join() method into String class to convert a List, Set, Collection, or even array of String objects to a comma-separated String in Java.

Can you join two unrelated tables in SQL? Cross Join Example

In one of the recent programming job interviews, one of my readers was asked the question, how do you join two tables which are not related to each other? i.e. they don't have any common column? is it possible in SQL? My reader got confused because he only knows about INNER join and OUTER join which require a key column like dept_id which is the primary key in one table like Department and foreign key in another table like Employee. He couldn't answer the question, though he did tell them about you can select data from multiple tables by typing multiple table names in from clause using a comma. 

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 the Class.forName() method. You should call this method with the correct 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 like mysql-connector-java-5.1.18-bin.jar depending upon which version of MySQL database you are connecting. 

How to use BigDecimal in Java? Example

Hello Java Programmers, if you are wondering how to use BigDecmial in Java then you have come to the right place. In this article, I will show you how to use BigDecimal for example in Java. BigDecimal is used to represent bigger numbers in Java, similar to float and long but many Java programmers also use BigDecimal to store floating-point values because it's easier to perform arithmetic operations on BigDecimal than float or double. That's the reason, many Java programmer uses BigDecmial for monetary or financial calculation that floats or double. 

Difference between Daemon Thread vs User Thread in Java? Example

A thread is used to perform parallel execution in Java 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 the 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 threads is live. JVM will wait for all active user threads to finish their execution before it shutdown itself. 

How to Fix java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Java [Solution]

Problem : You are getting java.lang.ClassNotFoundException: com.mysql.jdbc.Driver error while connecting to MySQL database from Java Program. You may be running your Java application directly from the command prompt, shell script, ANT or Eclipse.

Cause : In order to connect to MySQL database, you need JDBC driver for MySQL. A class that implements java.sql.Driver interface for MySQL. Every vendor is responsible to implement this class for their databases. This driver implementation is provided by MySQL as MySQL java connector library. There is a class called com.mysql.jdbc.Driver which implements this interface.

How to recursive copy directory in Java with sub-directories and files? Example

Hello guys, it's a common requirement in Java to copy a whole directory with sub-directories and files but it's not that straightforward, especially not until Java 7. JDK 7 introduced some new file utility methods as part of Java NIO 2 which we will use in this article to show you how to recursively copy a whole directory with sub-directories and files in Java. I'll also show you how you can use Apache Commons if you are not running on Java 7 or higher versions. Basically, You can copy a file or directory by using the copy(Path, Path, CopyOption...) method. The copy fails if the target file exists unless the REPLACE_EXISTING option is specified.

How to join two threads in Java? Thread.join() example

You can join two threads in Java by using the join() method from java.lang.Thread class. Why do you join threads? because you want one thread to wait for another before starts processing. It's like a relay race where the second runner waits until the first runner comes and hands over the flag to him. Remember, unlike sleep(), join() is not a static method so you need an object of java.lang.Thread class to call this method. Now, who calls and who wants, and which thread dies? for example, if you have two threads in your program main thread and the T1 which you have created. 

How to stop a thread in Java? Example

Today we're going to learn about how to stop a thread in Java. It's easy to start a thread in Java because you have a start() method but it's difficult to stop the thread because there is no working stop() method. Well, there was a stop() method in Thread class, when Java was first released but that was deprecated later. In today's Java version, You can stop a thread by using a boolean volatile variable.  If you remember, threads in Java start execution from the run() method and stop, when it comes out of the run() method, either normally or due to any exception. You can leverage this property to stop the thread. 

How to Fix java.lang.NullPointerExceptionin Java [Tips]

Hello Java programmers, if you want to learn what is NullPointerExcpeiton in Java and how to deal with ith then you have come to the right place. NullPointerException in Java is an unchecked Exception defined in java.lang package and comes when a member of an object either field or method is called on an object which is null. null is a keyword in Java that means nothing and the calling method on an object whose value is null will result in NullPointerException. Since the default value of Object is null, if you call any method or access any field on an Object which is not initialized will throw NullPointerException

5 Examples of Enhanced for loop in Java

Enhanced for loop was added way back in 2004 in Java and it provides an easy and cleaner way to iterate over array and Collection in Java. The introduction of forEach() in Java 8 has further improved iteration but that doesn't mean that you need to forget the for each loop. In this article, you'll see some cool examples of enhanced for loop in Java which will help you to write better and more readable code in Java. It's also less error-prone because you don't have to deal with an index like you need to with the classic "for" loop. This means no chance of one-off error, which means no risk of starting with index zero when you want to start with one or vice-versa.

Difference between StringTokenizer and Split method in Java? Example

There are multiple ways to split a String in Java, but two of the most common ways are by using StringTokenizer and the split method of String class. You can use either one of them, but when to use which one? This short article will give you some details about StringTokenizer and Split method in Java to decide which one to use.

1) The StringTokenizer is legacy, Prefer split() as more chances of its performance getting improved as happens in Java 7.

2) The StringTokenizer doesn't support regular expression, while spilt() does. However, you need to be careful, because every time you call split, it creates a new Pattern object and compiles expression into a pattern. This means if you are using the same pattern with different input, then consider using Pattern.split() method, because compiling a pattern takes more time later to check whether a given string matches a pattern or not.

How to solve Arithmetic overflow error converting IDENTITY to data type tinyint, smallint or int in Microsoft SQL Server database

Last year we had a production issue where one of our backup jobs was failing while inserting Orders aggregated from other systems into our SQL Server database. The reason was dreaded "Arithmetic overflow error converting IDENTITY to data type int" because the table was using IDENTITY feature of SQL Server to generate OrderId, and Identity has breached it a maximum value, which is around 2.1 billion, precisely 2,147,483,647. The error "Arithmetic overflow error converting IDENTITY to data type int" comes when the IDENTITY value is inserted into a column of data type int, but the value is out-of-range. For example, if the current value of Identity becomes more than 2,147,483,647, then you cannot store that into an int column because it's more than the maximum value of int in SQL Server.

Difference between the getRequestDispatcher and getNamedDispatcher in ServletContext? Example

The ServletContext class provides two methods getRequestDispatcher(String url-pattern) and getNamedDispatcher(String name), which can be used to dispatch a request to a particular servlet. The main difference between getRequestDispatcher() and getNamedDispatcher() method is that former accepts a URL pattern or path while later agrees with a Servlet name defined in deployment descriptor or web.xml file, both return an instance of RequestDispatcher class, which can further use to forward or redirect a request in Java web application. Let' see some more detail about these two methods and how they work.

What is Default or Defender Methods of Java 8 - Tutorial Example

Whenever someone talks about Java 8, the first thing they speak about is lambda expression and how lambda expression has changed the way you use Collections API today. In truth, lambda expression would not be that useful had language not been enhanced to support default methods on Java Interface. Also known as virtual extension or defender methods, they allow you to declare a non-abstract method inside the Java interface. This means, finally you can add new methods without breaking all classes, which implements a certain interface. This opens a new path for enhancing and evolving the existing Collection API to take advantage of lambda expressions. For example, now you can iterate over all elements of Collection in just one line, as opposed to four lines it requires you to do prior to Java 8.

How to Fix java.net.SocketException: Broken pipe in Java - Cause and Solution

Hello guys, If you have worked in a client-server Java application then you may be familiar with the  "java.net.SocketException: Broken pipe" error, It is one of the many socket-related errors you will see on the server-side application log.  This error comes intermittently when many clients are connecting to a server and many clients closing the connection before a response is fully transferred. Some of the common causes of java.net.SocketException: Broken pipe exception includes
  • The user closed the browser before the page loaded.
  • Their internet connection failed during loading.
  • They went to another page before the page loaded.
  • The browser timed the connection out before the page loaded (would have to be a large page).

How to Fix java.lang.VerifyError: Expecting a stack map frame at branch target 14 in method at offset JDK 7 [Solved]

Hello guys, today, we'll take a look at the not-so-common error for Java applications. If you have been working in Java for a couple of years then you might have seen this dreaded "java.lang.VerifyError: Expecting a stack map frame at branch target 14 in method at offset JDK 7" error in your application log or in Eclipse, particularly if you are running your Java application in Java 7. The main cause of this error, "java.lang.VerifyError: Expecting a stack map frame at branch target ... in the method ... at offset 0 error comes when you have some library, JAR file which is only compatible with Java 1.6 or below and you are running your program in JDK 1.7.

How to Fix "Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core” - Cause and Solution

This error comes in when you are trying to use the JSTL core tag library in your JSP page but the web container is not able to locate corresponding TLD files, also known as tag library descriptors. In order to use the custom tags in the JSP page, the first step is to import them using the @taglib directive and for that purpose, we provide a URI. Many JSP developer thinks this is the location where TLD files are stored but that's not true, this is actually the value, custom tab library developer has put in the URL field of tag library descriptor. This misunderstanding causes lots of trouble while solving "Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core”.

How to get current Page URL, Path, and hash using jQuery? Example, Tutorial

Hello guys,  in the last jQuery tutorial, I have taught you how to set and get values from a text field using jQuery and in this jQuery tutorial, you will learn about how to get the current URL and hash values, like something which starts with # (hash) letter. For example, in the URL http://localhost:8080/HelloWeb/test.html#ixzz2PGmDFlPd, URL is http://localhost:8080/HelloWeb/test.html and the hash value is ixzz2PGmDFlPd. This is important information and you will often find needing hash values from the current URL while working on a web application.

How to Find Nth Highest Salary in MySQL and SQL Server? Example LeetCode Solution

Nth Highest Salary in MySQL and SQL Server - LeetCode Solution
---------------------------------------------------------------
Write a SQL query to get the nth highest salary from the Employee table.

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.

How to do Inter process communication in Java? Example Tutorial

Hello guys, in the past, I have shown you how to do inter-thread communication in Java using wait-notify, and today, I will teach you how to do inter-process communication in Java. There are many ways to do inter-process communication in Java, you can use Sockets, both TCP and UDP, you can use RMI, you can use web services, or you can use memory-mapped file. The socket is the most common way of achieving inter-process communication if two processes are in two different hosts and connected via a network. RMI and WebService can also be used for similar purposes, but the last one, inter-process communication using memory-mapped files, is particularly useful if you are communicating with other processes in the same host, sharing the same memory and file system.

Top 24 Java Date, Time, and Calendar Interview Questions Answers

The Date and Time API is a significant one for day-to-day Java development work, but many interviewers don't ask enough questions on this topic. Most of the questions are based on either Java Collection framework like  HashMap, ConcurrentHashMap, or ArrayList or multi-threading concepts like volatile, synchronized, and atomic variables. This is not good, and many interviewers have realized that a good understanding of date and time API is also important for a good Java developer. That's the main reason for increasing date, time, and calendar-based Java interview questions in recent times, particularly in the last couple of years.

Java Interface Example for Beginners

Hello guys, if you are wondering what Java interface is and how to do your user interface in Java, you have come to the right place. Earlier, I have written about the actual use of the interface in Java, and in this article, I will give you an example of an interface in Java. I will also explain what an interface is and how and where you should use it. An interface is nothing but a name. As Joshua Bloch advised in the Effective Java book, the interface is great for declaring type. So, if you want to declare your own type like Employee, Order, Listener, etc., you can use the interface. 

How to Fix with java.net.SocketException: Connection reset Exception in Java? Examples

Hello guys, for the past few months, I have been writing about different socket-related errors on Java applications, and today I am going to talk about another common socket-related exception in Java -  java.net.SocketException: Connection reset Exception. There is no difference between exceptions thrown by the client and server. This is also very similar to the java.net.SocketException: Failed to read from SocketChannel: Connection reset by a peer but there is some subtle difference. The difference between connection reset and connection reset by peer is that the first means that your side reset the connection, the second means the peer did it. Nothing to do with clients and servers whatsoever

How to Solve String Anagram Coding Problem Solution in Java? Example

Hello guys, if you are preparing for Coding interviews then you already know that String is one of the most popular topics. You will be bound to get some string-based coding problems on interviews. If not, you have come to the right place becuase we'll look at one of the most popular String programming interview questions today,  how to check if two given strings are Anagram of each other? Two String is said to be an anagram of each other, if they contain exactly the same characters but in a different order. For example "ARMY" and "MARY" are an anagram of each other because they contain the exact same characters 'A', 'R', 'M' and  'Y'.

Top 5 Java EE Mistakes Java Web Developers should Avoid - Example

Hello guys, if you are working in Java EE and creating web applications and enterprise applications then you know that it's not as easy as it looks. You need to know some internal quirks so that your application can work properly in Production. Earlier, I have shared the free courses to learn full-stack Java development, and today, I am going to talk about some coding practices that you should avoid while creating Java web applications or Java EE applications. This will save you a lot of headaches when your application will go live and run in production. 

How to get current Day, Month, Year from Date in Java? LocalDate vs java.util.Date Example

In this article, I'll show you how to get the current day, month, year, and dayOfWeek in Java 8 and earlier version like Java 6 and JDK 1.7. Prior to Java 8, you can use the Calendar class to get the various attribute from java.util.Date in Java. The Calendar class provides a get() method which accepts an integer field corresponding to the attribute you want to extract and return the value of the field from the given Date, as shown here. You might be wondering, why not use the getMonth() and getYear() method of java.util.Date itself, well, they are deprecated and can be removed in the future version, hence it is not advised to use them.

How to use ConcurrentHashSet from ConcurrentHashMap in Java 8 - Example Tutorial

There is no ConcurrentHashSet in JDK 8, but you can still create one for yourself using the ConcurrentHashMap class of java.util. Concurrent package. A new method is added into ConcurrentHashMap in JDK 8, newKeySet(), which allows you to create a concurrent hash set backed by a concurrent hash map. If you remember, whenever you get keys from the map, they are returned in a Set e.g. for the old keySet() method, because the map only has unique keys. Since the map doesn't allow duplicate keys, it can be used as a set, as long as you only care for keys or just one element. 

How to Convert a LinkedList to an Array in Java? Example

You can convert a LinkedList to an array in Java by using the toArray() method of the java.util.LinkedList class. The toArray() method accepts an array of relevant type to store contents of LinkedList. It stores the elements in the array in the same order they are currently inside the LinkedList. By using the toArray() method you can convert any type of LinkedList e.g. Integer, String or Float to any type of Array, only catch is this you cannot convert a LinkedList to an array of primitives i.e. a LinkedList of Integer cannot be converted into an array of ints by using toArray() method, but you can convert it to an array of Integer objects, that's perfectly Ok.

Top 25 Exception Interview Questions for Java Programmers [UPDATED]

1) The difference between checked and Unchecked Exceptions in Java?
For checked exceptions, the compiler ensures that they are either handled using try-catch, try-finally, or try-catch-finally block or thrown away. If a method, which throws a checked exception like IOException, and doesn't handle them or doesn't declare them in the throws class of the method, a compile-time error will occur. On the other hand, the compiler doesn't do similar checks for an unchecked exception, that's why it is known as un-checked. These are also called runtime exceptions because they extend java.lang.RuntimeException.

How to convert int array to ArrayList of Integer in Java 8? [Example/Tutorial]

I once asked this question to one of the Java developers during an Interview and like many others, he answered that Arrays.asList() can convert an array of primitive integer values to ArrayList<Integer> in Java, which was actually wrong. Even though, Arrays.asList() is the go-to method to convert an Array to ArrayList in Java when it comes to converting a primitive array to ArrayList, this method is not useful. The Arrays.asList() method does not deal with boxing and it will just create a List<int[]> which is not what you want. In fact, there was no shortcut to convert an int[] to ArrayList<Integer> or long[] to ArrayList<Long> till Java 8.

Difference between Callable and Runnable in Java - Thread Interview question

The difference between the Callable and Runnable interface in Java is one of the interesting questions from my list of Top 15 Java multi-threading questions, and it’s also very popular in various Java Interviews. The Callable interface is newer than the Runnable interface and was added on Java 5 release along with other major changes e.g. Generics, Enum, Static imports, and variable argument method. Though both Callable and Runnable interfaces are designed to represent a task, which can be executed by any thread, there is some significant difference between them. 

10 Examples of LocalDate, LocalTime, and LocalDateTime in Java 8

It's been almost 5 years since Java SE 8 was released on 17th March 2014 and Java 8 adoption has come a long way. Java programmers around the world have accepted with both ends, many companies have switched their development on Java 8 and several others are migrating to Java 8 platform. At this time, it's extremely important for a Java developer to learn and share his Java 8 skill, and that just not include lambdas, stream, method reference, functional interface, and other more glamorous stuff, you also need to learn the new Date and Time API, which you would find using more regularly in your day to day life.

Why wait() and notify() method should be called inside a loop in Java? Example

If you have used the wait() and notify() method in Java then you know that the standard idiom of calling the wait() method uses a loop, but have you ever thought why? This is even advised by none other than Joshua Bloch, a Java guru and author of the popular Effective Java book, a must-read for any Java programmer. When I first started using this method, I was puzzled why not just use the if block because ultimately we are testing for a condition and then either waiting or going for further processing. An if block is more readable for the testing condition than a while loop like for the classic producer-consumer problem, the waiting condition for producer thread could be written as :

How to use Callable Statement in Java to call Stored Procedure? JDBC Example

The CallableStatement of JDBC API is used to call a stored procedure from Java Program. Calling a stored procedure follows the same pattern as creating PreparedStatment and then executing it. You first need to create a database connection by supplying all the relevant details e.g. database URL, which comprise JDBC protocol and hostname, username, and password. Make sure your JDBC URL is acceptable by the JDBC driver you are using to connect to the database. Every database vendor uses a different JDBC URL and they have different driver JAR which must be in your classpath before you can run the stored procedure from Java Program.

Top 10 Java Collections interview Questions Answers for Beginners

Hello guys, if you have gone through a couple of Java Interviews then you might know that Java Collections is an important topic. There is hardly any Java interview I have faced, and I have faced many where there are no questions from Collections. This Java Collection Framework interview questions and answers contain questions from popular Java collection classes like HashMap, ArrayList, HashSet, ConcurrentHashMap, and legacy collection classes like Vector and Hashtable. These are the questions that have been asked in real interviews and also allows you to explore these essential classes in more detail which will eventually make you a better Java developer. 

JDBC - How to connect MySQL database from Java program with Example

When you start learning JDBC in Java, the first program you want to execute is connected to a database from Java and get some results back by executing some SELECT queries. In this Java program, we will learn How to connect to the MySQL database from the Java program and execute a query against it. I choose the MySQL database because it's free and easy to install and set up. If you are using Netbeans IDE then you can connect MySQL Server directly from Netbeans, Which means in one window you could be writing Java code, and other you can write SQL queries.

5 ways to Compare String Objects in Java - Example Tutorial

here are many ways to compare String in Java e.g. you can use equals() and equalsIgnoreCase() for equality check and compare() and compareTo() for ordering comparison. You can even use the equality operator == to perform reference-based comparison e.g. to check both the String reference variable points to the same object. In general, equals() is used to check whether the value of a given String is the same i.e. they contain the same characters in the same sequence or not e.g. "Groovy".equals("Groovy") will be true if you compare them using equals() method. You can also use equalsIgnoreCase() to check if they are equal irrespective of case e.g. "Apple" and "apple" will be the same if you compare them using equalsIgnoreCase() method.

Top 10 Java Programming Coding Interview Questions Answers for programmers

Java coding interview questions answers
Java coding interview questions are mostly some programming exercises which is asked to be solved in the java programming language in a limited time during any core Java or J2EE interview. No matter whether you have 2 years of experience or 4 years of experience, there is always some coding interview question in the Java programming job you are applying for. Actually, questions related to Java Coding are increasingly getting popular in Java interviews for two reasons, first its difficult to crack Java coding interview questions than answering fact-based questions like Why String is immutable in Java or Why main is static in Java; Second reason of popularity of Coding question in Java interviews is read need of good developers who are required to do a lot of coding in projects rather than doing some maintenance works.

JDBC - How to connect Eclipse to Oracle Database - Step by Step Guide Example

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 the Execution plan in both text and Graphical mode, which you can use to troubleshoot the performance of your SQL queries.

JDBC - Difference between PreparedStatement and Statement in Java? Answer

If you have worked with database interfacing with Java using JDBC API then you may know that the JDBC API provides three types of Statements for wrapping an SQL query and sending it for execution to the database, they are aptly named as Statement, PreparedStatement, and CallableStatement. First, a Statement is used to execute normal SQL queries like select count(*) from Courses. You can also use it to execute DDL, DML, and DCL SQL statements. 

How to Convert Hostname to IP Address in Java - InetAddress Example

Hello guys, today, I am going to teach you about one interesting class from java.net package, the InetAddress. If you have never used this class before, let me tell you that it's an abstraction to represent an Internet address and it encapsulates both hostname and IP address. Since converting an IP address to hostname or hostname to IP address is a very common requirement, Java developers should know about this class, and, in general about java.net package, which contains many other useful class for networking and client-server applications. So, what is the best way to learn new APIs like java.net? Well, by writing small programs like this, which has a small focus and let you explore things. They are super useful and that's how I have learned the majority of Java API.

How to Convert a Comma Separated String to an ArrayList in Java - Example Tutorial

Suppose you have a comma-separated list of String e.g. "Samsung, Apple, Sony, Google, Microsoft, Amazon" and you want to convert it into an ArrayList containing all String elements e.g. Samsung, Apple, Google, etc. How do you do that? Well, Java doesn't provide any such constructor or factory method to create ArrayList from delimited String, but you can use String.split() method and Arrays.asList() method together to create an ArrayList from any delimited String, not just comma separated one. 

float and double data types in Java with Examples

Hello guys, float and double are two of the important data types in Java, but many developers don't pay enough attention to these two data types, resulting in writing poor code with subtle bugs. To be honest, they are not easy to use because of the complexity with floating-point calculation but knowing even simple things like the maximum and minimum limit of float and double data types and how to compare float and double variables can go a long way in eliminating bugs which are not obvious.

Top 10 Tough Core Java Interview Questions Answers for Programmers

tough core Java interviews questions and answers
What is a tough core java interview question? Why do people look for tough Java questions before going for an interview? well, I don't think I need to answer these tough questions because it's pretty natural to prepare for tough questions even if you are not expecting tough questions from core Java. If you are prepared for the tough and tricky Java interview question then you feel more confident and answer other Java interview questions with confidence. 

How to Run External Program, Command Prompt, and Batch files from Eclipse Console ? Example Tips

Hello guys, have you ever thought about how much time a Java developer spends on Eclipse, IntelliJ IDEA, or his favorite IDE? I guess most of his time, isn't it would be great to do as much as work possible from Eclipse itself, without switching to another application. Since switching between applications or programs requires some time, which is generally gone waste, I like to use Eclipse as much as possible, starting from coding in Java, executing Java programs to exploring XML files, and now even running the batch command from Eclipse. 

How to Show Open Save File Dialog in Java Swing Application? JFileChooser Example

Hello guys, if you worked in Java GUI-based application then you may know that Swing provides class javax.swing.JFileChooser can be used to present a dialog for the user to choose a location and type a file name to be saved, using the showSaveDialog() method. Syntax of this method is as follows:
   public int showSaveDialog(Component parent)

where the parent is the parent component of the dialog, such as a JFrame.

20+ JMS Interview Questions and Answers for Java Programmers

Java Messaging Service or JMS interview questions is one of the important parts of any Core Java or J2EE interview as messaging is a key aspect of enterprise Java development. JMS is a popular open-source Messaging API and various vendors like Apache Active MQ, Websphere MQ, Sonic MQ provide an implementation of Java messaging API or JMS. Any Java messaging services or JMS interview can be divided into two parts where the first part focuses on fundamentals of JMS API and messaging concepts like What is a topic, What is Queue, publish-subscribe or point to point model, etc, While the second part is related to JMS experience with particular JMS provider.

Java - Convert String to Short Example

In the last couple of examples, I have taught you how to convert String to Integer, Long, Double, Float, Boolean, and Byte in Java, and today I will show you how to convert String to Short in Java, but before that let's revise what is a short data type in Java. The short is an integral data type similar to the int but it only takes 2 bytes to store data as compared to 4 bytes required by an int variable. Since it takes only 2 bytes or 16 bits to store data, the range of short is also shorter than int. It ranges from -32,768 to 32767 (inclusive) or -2^15 to 2^15 -1. You might be wondering why the upper bound is 255 and the lower bound is -256 but that's because we have included zero in between.

5 Ways to implement Singleton Design Pattern in Java? Examples

This article introduces the singleton design pattern and its 5 implementation variations in Java. You will learn different ways to implement a singleton pattern and understand the challenges of creating a singleton class, like thread-safety issues and serialization issues.

Problem
At most, one instance of a class must be created in an application.

Solution
That class (singleton) is defined, including its own instance, and the constructor must be private.


Difference between VARCHAR and CHAR data type in SQL Server? [Explained]

Hello all, today, I am going to share an interesting SQL Server interview question, which will not only help you in your interview but also in your day-to-day work. It explains one of the critical concepts of SQL Server, the difference between VARCHAR and CHAR data type. I am sure, you all have used both of them numerous times but because it's so common many of us ignore the difference between them and when asked to choose between VARCHAR and CHAR on interviews, they fail to give a convincing reason. The difference is not just significant from an interview point of view but also from a robust database design because an incorrect choice of data type not only limit what kind of data you can put on but also waste precious space and makes your query slower, particularly when you have to deal with the massive amount of data.

How to Fix Access restriction: The type BASE64Decoder is not accessible due to restriction Error in Eclipse? [Solution]

Hello guys, if you have been using Eclipse for Java development then you might have seen this dreaded  "Access restriction: The type BASE64Decoder is not accessible due to restriction Error" before. This error comes when you are trying to encode String into Base64 using BASE64Decoder in Eclipse because the class BASE64Decoder is not part of JDK's public API, it comes from sun.misc package which is non-public. Though this class is present in JDK and JRE and allows you to encode and decode String into base 64, any access to this class from Eclipse flags as an error in Eclipse IDE. If you compile and run the same program from the command line or Netbeans you will not get this error.

Java CyclicBarrier Example for Beginners [Multithreading Tutorial]

This is the second part of my concurrency tutorial, in the first part, you have learned how to use CountDownLatch and in this part, you will learn how to use CyclicBarrier class in Java. CyclicBarrier is another concurrency utility introduced in Java 5 which is used when a number of threads (also known as parties) want to wait for each other at a common point, also known as the barrier before starting processing again. It's similar to CountDownLatch but instead of calling countDown() each thread calls await() and when the last thread calls await() which signals that it has reached the barrier, all threads started processing again, also known as a barrier is broken. 

How to Fix java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver [Solved]

Scenario : Your Java program, either standalone or Java web application is trying to connect to Oracle database using type 4 JDBC thin driver "oracle.jdbc.driver.oracledriver", JVM is not able to find this class at runtime. This JAR comes in ojdbc6.jar or ojdbc6_g.jar which is most probably not available in classpath.

Cause : When you connect to Oracle database from Java program, your program loads the implementation of Driver interface provided by the database vendor using class.forName() method, which throws ClassNotFoundException when driver class is not found in classpath. In case of Oracle the driver implementation is oracle.jdbc.driver.oracledriver and "java.lang.classnotfoundexception oracle.jdbc.driver.oracledriver" error indicate that this class is  not available in classpath. Since this class is bundled into ojdbc6.jar, its usually the case of this JAR not present in Classpath

How to Fix SQLServerException: The index 58 is out of range? JDBC Example

I was executing a stored procedure against SQL SERVER 2008 database from Java program using CallableStatement, but unfortunately, I was getting the following error "SQLServerException: The index 58 is out of range". Since I am passing a lot of parameters I thought that something is wrong with a number of parameters I was passing to the stored proc. My stored procedure had 58 INPUT parameters, as soon as I removed the 58th INPUT parameter the error goes away, which confirmed my belief that SQL Server supports a maximum of 57 INPUT parameters in stored procedure via JDBC

How to check if a File exists in Java with Example

Hello guys,  if you are working in Java for a couple of years, then you have come across a scenario where you need to check if a file exists or not. This is often required while writing defensive code that writes or reads from a file. While there is a method to check if a file exists in Java or not, it's not straightforward to use because it returns true if a given path represents a file or a directory. Yes, I am talking about the File. Exists () method of the java.io package. This method is the key method to solve this problem, but you need to keep in mind that it returns true if a given path exists and it's either file or directory. 

10 Things about Threads Every Java Programmer Should Know

Thread in Java is one of those topics which always confuse beginners but given the importance and strength it provides to the Java language, it's very important for every Java developer to learn and understand the fundamental concept of multi-threading and basic points about Thread in Java. I had started thread programming in Java by animating a couple of words in Applets, that was an amazing experience to code animation, but after spending almost 10 years on developing core Java applications and I am still discovering things about threading and concurrency. My first program which involves Thread had three words dropping from each corner of the screen and I was excited to see that animation driven by Java thread.

5 Difference between BufferedReader and Scanner class in Java? Example

Hello guys, welcome to my blog. Today, we'll discuss another interesting Java interview question, BufferedReader vs Scanner. It's not only important from an interview point of view but also to work efficiently with Java. Even though both BufferedReader and Scanner can read a file or user input from the command prompt in Java, there are some significant differences between them. One of the main differences between BufferedReader and Scanner class is that the former class is meant to just read String or text data while the Scanner class is meant to both read and parse text data into Java primitive types like int, short, float, double, and long.

How to Set Specific Java Version for Maven in Windows? Example Steps

Maven is a great build tool and most of the Java developer uses Maven to build their projects, but like any other tool, there are some intricacies which you need to know while using it. One of them is that Maven uses the Java version from the JAVA_HOME environment variable and not the PATH environment variable. If you have multiple JDK installed on your machine and getting an Unsupported major.minor version 51.0 or Unsupported major.minor version 52.0 error while building your project but have right Java version in PATH then you may need to check the JAVA_HOME and update it. If you don't have access to do it then you can still change JAVA_HOME using the set command in your local shell and run the Maven's mvn command to build the project

How to Fix javax.net.ssl.SSLHandshakeException: unable to find valid certification path to requested target in Java

Hello guys, this is one of the common errors in a client-server application. The big problem in solving this error is not the error but the knowledge of how client-server SSL handshake works. I have blogged about that before and if you have read that you know that in order to connect to any website or server (like LDAP Server) using SSL, you need to have certificates (public keys) to validate the certificates sends by the website you are connecting. If you don't have the root certificate or public key, which is required to validate the certificate presented by the server in your JRE truststore then Java will throw this error.

5 Tips to Fix ReferenceError: $ is not defined in jQuery and JavaScript [Solved]

Hello JavaScript developer, if you are wondering how to fix the RfrenceError $ is not defined while using jQuery then you have come to the right place. "ReferenceError: $ is not defined" is one of the common JavaScript errors which come when you try to use $, which is a shortcut of jQuery() function before you load the jQuery library like calling $(document).ready() function. "ReferenceError: XXX is not defined" is a standard JavaScript error, which comes when you try to access a variable or function before declaring it. Since jQuery is also a JavaScript library, you must first include the declaration of the jquery function or $() before you use it.

Difference between int and Integer Types in Java? Example

Both int and Integer are two important data types in Java that often cause confusion between new Java developers. Both int and Integer are used to represent numeric data and related to each other in the sense of primitive and Object. Int is a primitive data type that has 32-bit and stores values from  -2^31 to 2^31-1 while Integer is a class that wraps an int primitive inside it. In this article, you will learn why we need Integer Class in Java, particularly, if we already had the int data type, how to convert from int to Integer in Java, and various points on Integer in Java, ranging from basics to advanced BigInteger and AtomicInteger stuff.

Difference between WHERE and HAVING clause in SQL? Example

The main difference between the WHERE and HAVING clauses comes when used together with the GROUP BY clause. In that case, WHERE is used to filter rows before grouping, and HAVING is used to exclude records after grouping. This is the most important difference, and if you remember this, it will help you write better SQL queries. This is also one of the important SQL concepts to understand, not just from an interview perspective but also from a day-to-day use perspective. I am sure you have used the WHERE clause because it's one of the most common clauses in SQL along with SELECT and used to specify filtering criteria or conditions.

How to Fix Unsupported major.minor version 60.0, 59.0, 58.0, 57.0, 56.0, 55.0, 54, 0, 53.0, 52.00, 51.0 Error in Eclipse & Java

The UnsupportedClassVersionError is a big nightmare for Java developers, probably the next biggest after NoClassDefFoundError and ClassNotFoundException but it's slightly easier to solve. The root cause of this error is that your code is compiled using a higher JDK version and you are trying to run it on the lower version. For example, the Unsupported major.minor version 53.0 means your code is compiled in JDK 9 (the class version 52 corresponds to JDK 9) and you are trying to run it on any JRE lower than Java 9, probably JDK 8, 7, or 6.

How to Fix java.sql.BatchUpdateException: Error converting data type float to numeric - Java + SQL Server

This error can come if you are inserting or updating a NUMERIC column in the Microsoft SQL Server database from a Java Program using the executeUpdate()method, I mean executing a  batch update query. It could also happen if you are calling a stored procedure and passing a float value corresponding to a NUMERIC column, and the value happened to be out-of-range like generating "Arithmetic overflow error converting numeric to data type numeric" on the SQL Server end. For example, if your column is defined as NUMERIC (6,2) the maximum value it can represent is 9999.99, not 999999.99

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

Recently I was working in a Java application that uses Microsoft SQL Server at its backend. The architecture of the Java application was old i.e. even though there was heavy database communication back and forth there was no ORM used like no Hibernate, JPA, or Apache iBatis. The Java application was using an old DAO design pattern, where the DB related classes which are responsible for loading and storing data from the database was calling the stored procedure to do their job. These stored procedures take data from Java applications and insert it into SQL Server tables.

What is Method Overriding in Java ? Example Tutorial

Method overriding in Java
Method overriding in Java is a concept based on polymorphism OOP concept allows the programmer to create two methods with the same name and method signature on the interface and its various implementation and the actual method is called at runtime depending upon the type of object at runtime. Method overriding allows you to write flexible and extensible code in Java because you can introduce new functionality with minimal code change. Method overriding is different than the method overloading in Java which we have discussed in the last article.

15 People Java Developers Should Follow on Twitter

If you are passionate about Java and would like to follow Java bloggers into Twitter then here is my list of 15 people you can follow on Twitter to keep yourself up-to-date and engage in the Java world. These people regularly share the latest things in Java, JVM, Spring, Hibernate, and other Java technology. By following them, you will not only know about their latest work but also what's happening in the Java world. You might be thinking just 15 people, well, there are many more who is not on this list but I regularly share their Twitter handles via my Twitter account @javinpaul and @Javarevisited. If you are following me then you will automatically get to know about them.

How to append text to file in Java? Example Tutorial

Hello guys, In this article, I'll teach you how to append text to a file in Java. Earlier, I have taught you guys how to create a file and write text into it, but, append is totally different than creating a new file and writing data into it. In the case of append, the file already exists and you just add text at the end of the file. One popular example of appending text into a file is a log file that is constantly updated because your application continuously appends log details into it. While you don't need to create a logging framework here, just knowing how to append text into an existing file in Java is useful for Java programmers of all kinds of experience.

Difference between == and === Equal Operator in JavaScript

In one of the recent JavaScript interview for a Java web development position, one of my readers was asked this questions, What is the difference between comparing variables in JavaScript using "==" and "===" operator?  My reader got shocked because he was from Java background and doesn't have great exposure to JavaScript, though he was pretty much familiar with some JavaScript function, event handling, and some jQuery tricks, he wasn't aware of subtle details of JavaScript. He did the right think, politely said that he is not aware of the difference between == and === operator. Though It did not affect his interview performance much, he was keen to know about this as soon as he finished his interview. He asked to me as well, and that's the reason of this post. 

What is Thread and Runnable in Java? Example

What is Thread in Java?
Thread in Java is an independent path of execution that is used to run two tasks in parallel. When two threads run in parallel that is called multithreading in Java. Java is multithreaded from the start and has excellent support of Thread at language level e.g. java.lang.Thread class, synchronized keyword, volatile and final keyword make writing concurrent programs easier in Java than any other programming language like C++. Being multi-threaded is also a reason for Java's popularity and being the number one programming language. 

How to Remove All white spaces from String in Java? From Start, End and Between Words Examples

String API in Java provides several utility methods to remove white space from String in Java, from the beginning, end, and between words. White space means blank space including tab characters. One of the classic methods to remove white space from the beginning and end of a string in Java is the trim() method, which removes white space from beginning and end. While using the trim() method, the key thing to remember is that trim() returns a different String object than the older one because String is immutable in Java

How Constructor Chaining works in Java - Example

How to call one constructor from another constructor in Java or What is Constructor Chaining in Java is one of the tricky questions in Java interviews. Well, you can use this keyword to call one constructor from another constructor of the same class if you want to call a constructor from a based class or super class then you can use the super keyword. Calling one constructor from another is called Constructor chaining in Java. Constructors can call each other automatically or explicitly using this() and super() keywords. this() denotes a no-argument constructor of the same class and super() denotes a no argument or default constructor of the parent class. Also having multiple constructors in the same class is known as constructor overloading in Java.