Saturday, July 31, 2021

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. 

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. 

Friday, July 30, 2021

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 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.

Wednesday, July 28, 2021

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.

Tuesday, July 27, 2021

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. 

Monday, July 26, 2021

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 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. 

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.

Sunday, July 25, 2021

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.

Saturday, July 24, 2021

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 "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.

Friday, July 23, 2021

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

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 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.

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.

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.

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.

Thursday, July 22, 2021

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.

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.

Wednesday, July 21, 2021

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. 

Tuesday, July 20, 2021

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.

Monday, July 19, 2021

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.

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

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.

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.

Sunday, July 18, 2021

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.

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. 

What is blank final variable in Java - Example

What is a blank final variable in Java?
The blank final variable in Java is a final variable that is not initialized while declaration, instead they are initialized in a constructor. Java compiler will complain if a blank final variable is not initialized during construction. If you have more than one constructor or overloaded constructor in your class then a blank final variable must be initialized in all of them, failing to do so is a compile-time error in Java. Alternatively, you can use constructor chaining to call one constructor from another using this keyword, in order to delegate initialization of a blank final variable in Java. In this Java tutorial, we will see what is blank final variable is in Java and a code example on How to use a blank final variable.

Access Modifiers in Java - Public, Private, Protected, and Package Examples

public, private, protected and package or default are four access modifiers available in Java. These access modifiers provide Java programmers to control the accessibility or visibility of a class, method, or any field of a class. A good understanding of public, private, or protected modifiers is required in order to implement proper encapsulation in Java and create a Java program that is easier to maintain. In this Java tutorial, we will see what is public, private, protected and default modifiers are, which modifiers can be used with top-level class and nested class, and what is the difference between public, private, protected, and default modifiers in Java.

Top 50 Servlet and Filter Interview Questions Answers for Java/JEE developers

Hello Java web developers, if you are preparing for Java Developer interviews and want to prepare Servlet, one of the cores of Java web technology and the backbone of many popular MVC frameworks in the Java world like Spring and Struts then you have come to the right place. Earlier, I have shared free Servlet and JSP courses and in this article, we'll discuss some of the frequently asked, simple, and difficult Servlet interview questions from telephonic interviews of Java web development roles. The list includes frequently asked Servlet questions on key concepts like Servlet life cycle, how Servlet works in Tomcat or a web container, Servlet 3 annotations, Filters, Listeners, and how to customize initialization of Servlet. 

How to display date in multiple timezone in Java with Example - PST GMT

We can use SimpleDateFormat class to display a date in multiple Timezone in Java. While working in a global Java application it's quite common to display dates in the different time zone, classical example is Server is running on either PST or GMT timezone and clients are global or at least running on global trading hubs like Hong-kong, Mumbai, Tokyo, London, etc. Unfortunately, the Date and Time API in Java is quite tricky and until you have a good understanding of Date and Time classes and methods like Calendar, SimpleDateFormat, and thread-safety issues, You can easily create bugs. 

JDBC - How to Convert java.sql.Date to java.util.Date in Java with Example

How to convert java.sql.Date into a java.util.Date and vice-versa is a popular JDBC interview question which is also asked a follow-up question of the difference between java.sql.Date and java.util.The date which we have seen in our last article. Since both SQL date and Util date store values as a long millisecond, converting them back and forth is easy. Both java.sql.Date and java.util.The date provides a convenient method called getTime() which returns a long millisecond equivalent of a wrapped date value. Here is a quick example of converting java.util.Date to java.sql.Date and then back to util Date. 

5 Essential JDK 7 Features for Java Programmers

What is new in Java or JDK 7
It's close to a year now JDK 7 or Java 7 has been released, still, programmer asks what is new in Java 7 ? What is the best feature introduced in JDK7, where is the list of all Java 7 new features, etc? I thought to let's document Top 5 new features introduced in Java 7 for easy reference, this will not only answer What is new in Java 7 but also provide a quick overview of What are those features in Java 7.  Java 7 introduced many new features in Java programming language like try-catch with a resource, String in Switch, etc but it also makes a lot of changes on Java Development API by introducing a new File API in Java and several other minor changes. Like you can now find hidden files from the Java programs without applying any hack. anyway let's see my list of Top 5 Java 7 features :

Difference between DOM vs SAX Parser in Java - XML Parsing in Java

DOM vs SAX parser in Java
DOM and SAX parser are the two most popular parsers used in the Java programming language to parse XML documents. DOM and SAX concept is originally XML concept and Java programming language just provide an API to implement these parsers. Despite both DOM and SAX are used in XML parsing, they are completely different from each other. In fact difference between DOM and SAX parser is a popular Java interview question asked during Java and XML interviews. DOM and SAX parser has a different way of working, which makes Java programmer understand the difference between DOM and SAX parser even more important.

How to configure Daily Log File Rolling in Java using Log4j - DailyRollingFileAppender Example

Hello guys, today, I am going to share one small but the useful tip about logging in to your Java application. If your Java application is a weekly restart, I mean it starts on Sunday and not again on the weekday, then you really want to have separate log files for each day. This helps during troubleshooting and debugging. But If you are facing a problem where your log files are not rolling daily and becoming bigger and bigger after each passing day, making it challenging to search anything in case of any production issue, then it might be that you have not configured your Log4j properly to roll your logs daily.

Saturday, July 17, 2021

Difference between static and non static nested class in Java? Example

Static vs. non Static class in Java
In Java, you can make a class either static or non-static. Now, what is the difference between making a class static vs. non-static? Well, there is a lot of difference between them. First of all, there are two kinds of classes in Java, one is called a top-level class, and the other is called a nested class. As the name suggested, a top-level class is a class that is declared in the .java file and not enclosed under any other class. On the other hand, a nested class is declared inside another class. The class which enclosed nested class is known as Outer class. 

Eclipse and NetBeans Keyboard Shortcuts for Java Programmers - Example

If you are a Java developer who has been using Eclipse for Java development, but you need to use Netbeans for your current project for various reasons, this article is for you. Whenever we transition between tools, we need the equivalent of one into other. For example, if you are an Eclipse power user who is used to Ctrl + Shift + R and Ctrl + Shift + T, you miss those as soon as you start using Netbeans shortcuts. One thing to keep your productivity up is to quickly find the equivalent shortcut in a new tool, like, Netbeans if you are switching from Eclipse or vice-versa.

Friday, July 16, 2021

How to read file in Java using Scanner Example - text files

Reading a file with Scanner
From Java 5 onwards java.util.Scanner class can be used to read file in Java. Earlier we have seen examples of reading file in Java using FileInputStream and reading file line by line using BufferedInputStream and in this Java tutorial, we will See How can we use Scanner to read files in Java. Scanner is a utility class in java.util package and provides several convenient methods to read int, long, String, double etc from a source which can be an InputStream, a file, or a String itself.

How to convert int value to a Long object in Java? Examples

Suppose you have an int variable but the part of the application is expecting a Long object, how do you convert a primitive int to a Long object in Java? It shouldn't be a problem, right? after all long is a bigger data type than int, so all int values are acceptable as long, but we also need a Long object, not just the long primitive value. Now, the problem is reduced to converting a long primitive to a Long object, which is not really a problem if you are running on a JRE version higher than Java 5. But, sometimes autoboxing is not efficient like when you have to convert multiple long values into the Long object in a loop. 

Wednesday, July 14, 2021

Difference between Primary key vs Candidate Key in SQL Database? Example

Primary key vs Candidate Key
What is the difference between primary key and candidate key is another popular SQL and database interview question which appears in various programming interviews now and then? The concept of primary key and candidate key is not just important from the interview point of view but also in designing databases and normalization. By the way, this is my second post about primary keys, In the last one, we have seen a comparison of primary key vs unique key, which also happens to be one of the frequently asked database questions. 

How to Create Random Alphabetic or AlphaNumeric String of given length in Java? SecureRandom Example

Hello Java programmers, if you want to create a random alphanumeric string and looking for examples then you have come to the right place. Earlier, I have shown you how to generate random numbers in a range, and in this article, you'll learn how to generate random alphanumeric String in Java. Suppose, you want to generate an alphabetic or alphanumeric string of a given length in Java? How do you do it? Well, if you are like me, you probably search a library like Apache commons-lang or Google Guava for something which can do this task. It's a good thing. There is no point in re-inventing a wheel if a tried and tested solution already exists. In fact, Effective Java, the most respected book in the Java world also suggests knowing and use your library. 

How to Order and Sort Objects in Java? Comparator and Comparable Example

Java Object Sorting Example
How do you sort a list of Objects in Java is one of the frequently asked coding questions in Java interviews and surprisingly not every Java programmers know How sorting of object happens in Java. Comparator and Comparable interface along with Collections.sort() method are used to sort the list of objects in Java. compare() and compareTo() method of Comparator and Comparable interface provides comparison logic needed for sorting objects. compareTo() method is used to provide Object's natural order sorting and compare() method is used to sort Object with any arbitrary field. 

Tuesday, July 13, 2021

Difference between int and Integer data type in Java? Example

The first and foremost difference between an int and Integer or a char and Character is that the former is a primitive data type while the latter is a class, also known as wrapper class because they wrap the primitive data type inside it. When you first start learning Java, you start with primitive data types like int, long, char, byte, boolean, float, and double but slowly you learn about Object, and sometime later you know about Integer, Long, Character, Byte, Boolean, Float, and Double. At this point in time, you may wonder, what is the real difference between an int and Integer? isn't both the same? We can pass Integer where int is expected and vice-versa then why on the earth we have both int and Integer?

JDBC - How to get Row and Column Count From ResultSet in Java? Example

One of the common problems in JDBC is that there is no way to get the total number of records returned by an SQL query. When you execute a Statement, PreparedStatement, or CallableStatement using execute()or executeQuery() they return ResultSet and it doesn't have any method to return the total number of records it is holding. The only way to find the total number of records is to keep the count while you are iterating over ResultSet while fetching the result. This way, you can print the total number of rows returned the SQL query but only after you have processed all records and not before, which may not be the right way and incur significant performance cost if the query returns a large number of rows.

Difference between Clustered and Non-Clustered Indexes in Database? SQL Question Answer

Clustered vs Nonclustered Indexes in SQL
The difference between Clustered and Nonclustered index in a relational database is one of the most popular SQL interview questions almost as popular as the primary key vs unique key, the difference between truncate and delete, and correlated vs noncorrelated subqueries. Indexes are a very important concept, it makes your queries run fast and if you compare a SELECT query which uses an indexed column to one who doesn't you will see a big difference in performance. 

How to use jQuery First time? HelloWorld Example

What is jQuery
jQuery is nothing but a JavaScript library that comes with rich functionalities. It's small and faster than many JavaScript codes written by an average web developer. By using jQuery we can write less code and do more things, it makes web developer's tasks very easy. In simple words, jQuery is a collection of several useful methods, which can be used to accomplish many common tasks in JavaScript. A couple of lines of jQuery code can do things that need too many JavaScript lines to accomplish. The true power of jQuery comes from its CSS-like selector, which allows it to select any element from DOM and modify, update or manipulate it. 

How to convert Timestamp to Date in Java?JDBC Example Tutorial

In the last article, I have shown you how to convert Date to Timestamp in Java and today we'll learn about converting timestamp value from database to Date in Java. As you remember, the JDBC API uses separate Date, Time, and Timestamp classes to confirm DATE, TIME, and DATETIME data type from the database, but most of the Java object-oriented code is written in java.util.Date. This means you need to know how to convert the timestamp to date and vice-versa. You can do by using the getTime() method, which returns the number of millisecond from Epoch value. 

Difference between throw vs throws in Java? Answer

throw vs throws in Java
throw and throws are two Java keywords related to the Exception feature of the Java programming language. If you are writing a Java program and familiar with What is Exception in Java, it's a good chance that you are aware of What is throw and throws in Java. In this Java tutorial, we will compare throw vs throws and see some worth noting differences between throw and throws in Java. Exception handling is an important part of the Java programming language which enables you to write robust programs. There are five keywords related to Exception handling in Java like try, catch, finally, throw, and throws.

How to read User Input from Console in Java? Scanner Example

Apart from reading files, Scanner can also read user input from Console in Java. Just like in the case of reading files, we have provided File as a source for scanning, We need to provide System.in as a source to scan for user input in Console. Once you created and initialized java.util.Scanner, you can use its various read method to read input from users. If you want to read String, you can use nextLine(), if you want to read integer numbers, you can use nextInt(). 

How to Find IP address of localhost or a Server in Java? Example

In today's Java programming tutorial, we will learn some networking basics by exploring the java.net package. One of the simple Java network programming exercises, yet very useful, is to write a program to find the IP address of the local host in Java. Sometimes this question is also asked to find the IP address of the Server on which your Java program is running or find the IP address of your machine using Java etc. In short, they all refer to localhost. For those who are entirely new in the networking space, there are two things to identify a machine in a network, which could be LAN, WAN, or The Internet. 

Can You Create Instance of Abstract class in Java? Answer

Hello Java Programmers, how are you doing? Hope you are doing well. It's been a long since  I shared a core Java interview question in this blog, so let's start with that. Earlier I have shared one of the frequently asked questions in Java, can we make an abstract class final in Java and my readers really liked it and asked for more such questions. So, today I am going to talk about whether you can create an instance of an Abstract class in Java or not? This is another interesting core Java question that you will find on telephonic interviews, a written test that has multiple-choice questions and most notably Oracle certified Java programmer certification like OCAJP 8  and OCAJP 11.

Monday, July 12, 2021

Difference between include directive, include action and JSTL import tag in JSP? Answer

There are three main ways to include the content of one JSP into another:

include directive

JSP include action

and JSTL import tag

The include directive provides static inclusion. It adds the content of the resource specified by its file attribute, which could be HTML, JSP, or any other resource at translation time.

Any change you make in the file to be included after JSP is translated will not be picked up by the include directive.

Difference between Primary key vs Unique key in SQL Database? Answer

primary key vs unique key in SQL
The primary key and unique key are two important concepts in a relational database and are used to uniquely identify a row in a table. Both primary key and unique keys can identify a row uniquely but there is some subtle difference between them which we will see in this article. In fact, primary key vs unique is a popular SQL interview question along with classics like truncate vs delete and  How to manage transactions in a database, mostly asked to fresher and 2 to 3 years experience guys in any programming language. SQL is not just limited to any DBA or PLSQL developer but it's an important skill even for Java programmers and you can expect SQL interview questions even in many Java interviews.

How to convert String to Enum in Java? ValueOf Example

valueOf Example in Java Enum
valueOf method of Java Enum is used to retrieve Enum constant declared in Enum Type by passing String in other words valueOf method is used to convert String to Enum constants. In this Java Enum valueOf example we will see how to use the valueOf method in Java. valueOf method is implicitly available to all Java Enum because every enum in Java implicitly extends java.lang.Enum class. valueOf method of enum accepts exactly the same String which is used to declare Enum constant to return that Enum constant. valueOf method is case-sensitive and invalid String will result in IllegalArgumentException.

The Ultimate Guide to Package in Java? Examples

If you are learning Java then you might have come across a package concept and if you are wondering what is package and why should we use it then you have come to the right place. In this article, I will explain what is package in Java and other stuff around the package, including some best practices which using the package in Java. In the simplest form, a package is a way to organize related functionality or code in a single place in Java. If you look from a File System perspective then a package in Java just represent a directory where Java source file is stored in compilation and class files are stored after compilation. 

How to read a file line by line in Java? BufferedReader Example

Hello Java Programmers, if you are looking for a way to read a file line by line in Java then don't worry, Java provides java.io  package in JDK API for reading File in Java from File system e.g. C:\ or D:\ drive in Windows or any other directory in UNIX. First, you can use FileInputStream to open a file for reading. FileInputStream takes a String parameter which is a path for the file you want to read. Be careful while specifying File path as path separator is different on Window and UNIX. Windows uses backslash while UNIX uses forward slash as a path separator. 

How to create and initialize List or ArrayList in one line in Java? Example

creating and initializing List at the same time
Sometimes we want to create and initialize a List like ArrayList or LinkedList in one line much like creating an array and initializing it on the same line. If you look at The array on Java programming language you can create and initialize both primitive and object arrays e.g. String array very easily in just one line but in order to create a List equivalent of that array, you need to type a lot of code. This is also one of the tricky Java question sometimes appears in Interview as Write Java code to create and initialize ArrayList in the same line.

Sunday, July 11, 2021

Java Enum with Constructor Example

Java Enum with Constructor
Many Java developers don't know that Java Enum can have a constructor to pass data while creating Enum constants. This feature allows you to associate related data together. One example of passing arguments to enum Constructor is our TrafficLight Enum where we pass the action to each Enum instance e.g. GREEN is associate with go, RED is associated with stop, and ORANGE is associated with the slow down

Difference between ServletConfig and ServletContext in JSP Servlet? Answer

Difference between ServletConfig and ServletContext
ServletContext and ServletConfig these two are the important interface of Servlet API which is used by Java J2EE programmer during web application development. Correct understanding of What is ServletContext and ServletConfig is very important for any J2EE application developer. Apart from that Difference between ServletContext and ServletConfig are a popular Servlet JSP interview questions and mostly asked on both fresher and experienced Java programmer during J2EE interviews. 

Could not create the Java virtual machine Invalid maximum heap size: -Xmx

"Could not create the Java virtual machine" is a general JavaVirtual Machine error when you run java command directly or indirectly and it's not able to create a virtual machine because of invalid maximum heap size, invalid minimum heap size, or just an error in command line. This error not only come when you run Java program from the command line but also when you run them using any IDE like Eclipse or Netbeans.

ArrayList vs Vector in Java? Interview Question Answer

ArrayList vs Vector in Java
ArrayList and Vector are the two most widely used Collection classes in Java and are used to store objects in an ordered fashion. Every Java programmer which is introduced to Java Collection Framework either started with Vector or ArrayList. For beginners Difference between Vector and ArrayList in Java and LinkedList vs ArrayList are the two most popular Java Interview questions. ArrayList vs Vector is not only important from an interview perspective but also on the effective use of Java Collection API. 

Friday, July 9, 2021

The Ultimate Guide of Enum in Java - Examples

Apart from the Class and Interface, Enumeration type or Enum is another popular type in Java programming language. Enum allows you to represent a fixed number of well-known things in a type-safe manner e.g. days of the week, days of the month, planets in the solar system, buttons on the remote control, keys on the keyboard, and suits on playing cards. Before Enum was introduced, prior to Java 1.5, integer and string constants are used to represent the fixed number of things, known as enum int pattern and enum string pattern as described in classic Effective Java by none other than Joshua Bloch. Though they served the purpose, they had some major drawbacks which resulted in poor quality code.

What is class file in Java? Example

What is the class file in Java?
Class file in Java is compiled from of Java source file. When we compile a Java program written in a Java source file ended with a .java extension, it produces one more class file depending upon how many classes are declared and defined in that Java source file. One Java source file can only contain one public class, and its name must match with the name of the file like HelloWorld.java file can contain a public class whose name should be HelloWorld as shown below :

Wednesday, July 7, 2021

How to fix java.lang.OutOfMemoryError: unable to create new native thread [Solution]

There are several types of OutOfMemoryError in Java e.g. OutOfMemoryError related to Java heap space and permgen space, and a new one coming in Java 8, Java.lang.OutOfMemoryError: Metaspace. Each and every OutOfMemoryError has its own unique reason and corresponding unique solution. For example, java.langOutOfMemoryError: Java Heap Space comes when the application has exhausted all heap memory and tries to create an object which requires further memory allocation, At that time JVM throws this error to tell the application that it's not possible to create an object.