Wednesday, December 7, 2022

Is Java Pass by Value or Pass by Reference? Example

Hello guys, Does Java is pass by value or pass by reference is one of the tricky Java questions mostly asked on both beginner and experienced level Java developer interviews. Before debating whether Java is pass by value or pass by reference lets first clear what is pass by value and what is pass by reference actually means?. This question has its origin in C and C++ where you can pass function parameter either value or memory address, where value is stored (pointer). As per Java specification everything in Java is pass by value whether its primitive value or objects and it does make sense because Java doesn't support pointers or pointer arithmetic, Similarly multiple inheritance and operator overloading is also not supported in Java.

Wednesday, September 21, 2022

Difference between CAST, CONVERT, and PARSE SQL Server? Example Tutorial

Though all three, CAST, CONVERT, and PARSE are used to convert one data type into another in SQL Server, there are some subtle differences between them. The  CAST method accepts just two parameters, expression, and target type, but CONVERT() also takes a third parameter representing the format of conversion, which is supported for some conversions, like between character strings and date-time values. For example, CONVERT(DATE, '2/7/2015', 101) converts the character string '2/7/2015' to DATE using DATE format 101, representing United States standard.

Tuesday, August 30, 2022

Difference between @Mock and @MockBean in Spring Boot? Example Tutorial

Hello guys, if you are writing test for your your Spring Boot application then Sooner or later, you'll come across @Mock and @MockBean annotations while testing your Spring Boot application. Both annotations generate fake or Mock  objects, but for different reasons and its important for Java and Spring Boot developer to know the correct difference and when to use @Mock and @MockBean while writing tests. It's possible that this will seem perplexing at first, in face I was confused for a long time until I did my research and cleared it up. But, you don't need to scan through internet, In this blog article, I'll clear up any misunderstandings and clarify the difference between @Mock and @MockBean when testing Spring Boot apps.

Saturday, August 27, 2022

Difference between State and Strategy Design Pattern in Java

Hello guys, if you are wondering what is difference between State and Strategy pattern in Java then you are at the right place. In order to make proper use of State and Strategy design Patterns in any Java application, it's important for a Java developer to clearly understand the difference between them. Though both State and Strategy design patterns have a similar structure, and both of them are based upon the Open closed design principle, which represents 'O' from SOLID design principles, they are totally different on their intent. The strategy design pattern in Java is used to encapsulate a related set of algorithms to provide runtime flexibility to the client. 

Decorator Design Pattern in Java with Example Java Tutorial

Hello guys, if you want to learn about Decorator design pattern in Java then you are at the right place. I was thinking to write on decorator design pattern in Java when I first wrote 10 interview questions on Singleton Pattern in Java. Since design patterns are quite important while building software and it’s equally important on any Core Java Interview, It’s always good to have a clear understanding of various design patterns in Java. In this article, we will explore and learn the Decorator Design pattern in Java which is a prominent core Java design pattern and you can see a lot of its examples in JDK itself. 

Data Access Object (DAO) design pattern in Java - Tutorial Example

Data Access Object or DAO design pattern is a popular design pattern to implement the persistence layer of Java application. DAO pattern is based on abstraction and encapsulation design principles and shields the rest of the application from any change in the persistence layer e.g. change of database from Oracle to MySQL, change of persistence technology e.g. from File System to Database. For example, if you are authenticating the user using a relational database and later your company wants to use LDAP to perform authentication. If you are using the DAO design pattern to access the database, it would be relatively safe as you only need to make a change on Data Access Layer. DAO design pattern also keeps the coupling low between different parts of an application.

Thursday, August 25, 2022

How to Convert a Map to a List in Java - Example Tutorial

Hello guys, if you are wondering how to convert a Map like HashMap or TreeMap to a List like ArrayList or LinkedList in Java then you are at the right place. Earlier, I have shared 10 examples of converting a List to Map in Java and this article, I am going to share my tip to convert a given Map to a List in Java. Map and List are two common data structures available in Java and in this article, we will see how can we convert Map values or Map keys into List in Java. The primary difference between Map (HashMap, ConcurrentHashMap, or TreeMap) and List is that Map holds two objects key and value while List just holds one object which itself is a value. 

Wednesday, August 24, 2022

How to use mkdir command to make directories in Linux and UNIX? mkdir -p Example

One of the most common tasks in any Linux is creating directories, and most of us spend a lot of time creating complex directory structures in UNIX and Linux.  I am sure you know about the mkdir command, we have been using this command in almost every operating system like DOS, Windows, Linux, OS/2, Solaris, or any other *NIX operating system. It is one of the basic commands but as important as find, grep or chmod.  mkdir stands for "make directory" and this command is literally used to create directories. Suppose, you need to create a directory tree-like /opt/software/java/app/config, how are you going to create these directories? One by one right? Well, yes you can use mkdir and command to create these directories one by one as shown in below example :

Tuesday, August 23, 2022

How hostname to IP address Conversion works in Linux? nslookup Example

One of my favorite Linux Interview questions is about how to convert hostname to IP address in Linux? These questions not just test the candidate's basic Linux command skills but also shows his understanding of how name resolution works in UNIX or Linux? Many developers, software engineers, and support professionals don't really know how Linux converts a hostname into IP address or what happens when they type http://www.amazon.com in their browser in UNIX? They are not really familiar with how the name amazon.com is resolved to an IP address.

Monday, August 22, 2022

How to Delete Empty Files and Directories in UNIX or Linux Host? find Command Example

Deleting empty file and directory in Unix
Hello guys, if you are wondering how to find and remove all empty files and directories from a Linux host then you are at the right place. Earlier, I have shared Linux command to free disk space by removing big files and directories and in this article, I will share find command you can use to remove empty files and directories. Many times we need to find and delete empty files or directories in UNIX/Linux. Since there is no single command in Unix/Linux which allows you to remove empty files or empty directories rather we need to rely on find command and xargs command

Saturday, August 20, 2022

Difference between HashMap, LinkedHashMap and TreeMap in Java with Example

Hello guys, if you are wondering what is difference between HashMap, TreeMap, and LinkedHashMap in Java and when to use them then you are at the right place. In past, I have shared frequently asked HashMap Interview questions and ConcurrentHashMAp Interview questions and today, I Will answer this question in detail. The java.util.Map is one of the most important interfaces from the Java Collection Framework.  It provides hash table data structure functionality by its implementations like HashMap, Hashtable, LinkedHashMap, and a little bit of sorting with the TreeMap. So if you are looking to store key-value pairs in the Java program,  you have a wide range of choices available depending upon your requirement. The main difference between LinkedHashMap, TreeMap, and HashMap comes in their internal implementation and specific features, which a Java programmer should know to use them effectively. 

Friday, August 19, 2022

4 Example to Iterate over Map, HashMap, Hashtable or TreeMap in Java

There are multiple ways to iterate, traverse or loop through Map, HashMap, or TreeMap in Java and we are all familiar with either all of those or some of those. But to my surprise, one of my friends was asked in his interview (he has more than 6 years of experience in Java programming) to write code for getting values from HashMap, Hashtable, ConcurrentHashMap, or TreeMap in Java in at least 4 ways. Just like me he was also surprised by this question but written it. I don't know why exactly someone asks this kind of java interview question to a relatively senior java programmer. Though my closest guess is to verify that whether he is still hands-on with coding in java. 

How to get Key From Value in Hashtable, HashMap in Java? Example

It's not easy to get key from the value in Hashtable or HashMap, as compared to getting value from key because HashMap or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. in fact, Map allows the same value to be mapped to multiple keys inside HashMap, Hashtable, or any other Map implementation. What you have in your kitty is Hashtable.containsValue(String value) or Hashtable.containsKey(String key) to check whether key or value exists in HashMap or not, but sometimes we want to retrieve a value from Map corresponding to any key and there is no API method to do in Map.

10 Examples of HashSet in Java - Tutorial

HashSet in Java is a collection that implements the Set interface and is backed by a HashMap. Since HashSet uses HashMap internally it provides constant-time performance for operations like add, remove, contains and size give HashMap has distributed elements properly among the buckets. Java HashSet does not guarantee any insertion orders of the set but it allows null elements. HashSet can be used in place of ArrayList to store the object if you require no duplicate and don't care about insertion order.

Thursday, August 18, 2022

Difference between HashMap and IdentityHashMap in Java? Example

Hello guys, if you are wondering what is differnece between an HashMap and IdentiyHashMap in Java then you are at right place. IdentityHashMap in Java was added in Java 1.4 but still, it's one of those lesser-known classes in Java. The main difference between IdentityHashMap and HashMap in Java is that IdentityHashMap is a special implementation of Map interface which doesn't use equals() and hashCode() method for comparing objects unlike other implementations of Map e.g. HashMap. Instead, IdentityHashMap uses the equality operator "=="  to compare keys and values in Java which makes it faster compared to HashMap and suitable where you need reference equality check and instead of logical equality.

Difference between bitwise and logical AND, OR Operators in Java? Examples

Java beginners often ask the same type of questions, and of them is what is the difference between & and && operator in Java or the difference between | and || operators? The standard answer to this question is well, the main difference between & and && is that the former is a bitwise operator, and && is a logical operator in Java. That's academic until you clearly explain the difference in working of & and && or | and ||. For absolute beginners, & is used to represent AND logic operation in Java and | is used to represent OR logic operation.

What is NavigableMap in Java ? TreeMap, headMap, tailMap, and subMap Examples

Hello guys, if you are wondering what is NavigableMap and why should Java developer know about it you are at right place. NavigableMap in Java is an extension of SortedMap  like TreeMap which provides convenient navigation methods like lowerKey, floorKey, ceilingKey, and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation methods it also provides ways to create a Sub Map from existing Map in Java, like headMap whose keys are less than the specified key, tailMap whose keys are greater than specified key and a subMap which strictly contains keys that falls between toKey and fromKey

Wednesday, August 17, 2022

Why use SerialVersionUID inside Serializable class in Java? Example

Serialization and SerialVersionUID always remain a puzzle for many Java developers. I often see questions like what is this SerialVersionUID, or what will happen if I don't declare SerialVersionUID in my Serializable class? Apart from the complexity involved and rare use, one more reason for these questions is Eclipse IDE's warning against the absence of SerialVersionUID e.g. "The Serializable class Customer does not declare a static final SerialVersionUID field of type long". In this article, you will not only learn the basics of Java SerialVersionUID but also its effect during the serialization and de-serialization process. 

Monday, August 15, 2022

Object Oriented Programming Example in Java? Tutorial

I remember when I was doing my engineering, the OOPS concept was in the first semester. Back then it looks like some alien things to me, because I have never done programming and even the smallest program we get to write like checking whether the number is palindrome or not, or printing the Fibonacci series, we never really needed to use OOPS. When needed, I just memorize things and write them down in exams :). That worked, I passed the exam but effectively I didn't learn OOP or Object Oriented Programming on those days.

Difference between Class, Instance and Local variables in Java? Example

There are a lot of differences between instance variable, class variable, and local variable in Java, and knowing them will help you to write correct and bug-free Java programs. Java is a full-featured programming language and provides different kinds of variables like static variables also called Class variable since it belongs to whole Class, non-static also called instance variable and local variables which vary in scope and value. Thank god Java doesn't have any register variable or auto scope like C Programming language, otherwise it would have so much detail to remember. static variables are a common source of error in may multi-threaded java program and does require a bit of carefulness while using it. On the other hand instance, the variable and the local variable have less sharing visibility than a static variable.

Friday, August 5, 2022

Difference between Checked vs Unchecked Exception in Java? Example

Checked and Unchecked Exception is two types of Exception exist in Java. Though there is no difference in functionality and you can very achieve the same thing with either checked Exception or Unchecked Exception, there is some difference on exception handling part. In this Java tutorial we will see what is checked and Unchecked Exception in Java, Examples of Checked and Unchecked Exception and most importantly we will learn when to use Checked Exception and when to use Unchecked Exception in Java and lastly we will see the difference between checked and unchecked exception to understand things better. 

[Solved] How to solve java.lang.UnsatisfiedLinkError: no ocijdbc11 in Java with Oracle 11g, 12c, 19c and 21c

"java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path" error comes when you try to connect to Oracle 11g database using OCI (thick) driver by using tns name, but the ocijdbc11.dll file is not available in PATH or java.library.path environment variable. ocijdbc11.dll is a native library and if you know Java searches native library in PATH or a location specified by java.library.path system property, if it doesn't find the dll, then it throws java.lang.unsatisfiedlinkerror no ocijdbc11 in java.library.path error. This dll is usually found in C:\Programs\Oracle\ora11g\bin\ocijdbc11.dll, but it could vary depending upon your Oracle installation.

Thursday, August 4, 2022

How to fix java.lang.UnsupportedClassVersionError: Bad version number in .class files? Example

How to fix Bad version number in the .class file
"java.lang.UnsupportedClassVersionError: Bad version number in .class file" is a common error in Java programming language which comes when you try to run a Java class file which was compiled by different version of Java compiler than then JRE version you are using to run it. In our last article, we discussed that how to resolve Java.lang.UnSupportedClassVersionError and found that it comes when a major and minor version of the class is not supported by Java virtual machine or JRE running the program. Though "java.lang.UnsupportedClassVersionError: Bad version number in .class file" is a little different than that of its manifestation and Cause, both are related to the mismatch in compiler javac and runtime java version. 

How to Fix Must Override a Superclass Method Error Eclipse IDE Java | @Override annotation with interface methods

One of the annoying error while overriding Java method in Eclipse IDE is must override a superclass method error, This error is quite frequent when importing Java projects and after so long, still I haven't seen any permanent solution to it. Must override a superclass method the error comes in Eclipse if you have Java Class that implements interface and overrides a method from interface and uses @Override annotation. Unfortunately, Eclipse defaults to Java 1.5, which only recognize @Override annotation for the overriding method from the superclass and not from the interface.

How to fix "No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK" in Eclipse & Maven?

If you are like many Java developer who uses Maven and Eclipse to build Java project using M2Eclipse plugin, you might have seen this error before. I ran into it recently when I ran the Maven Install command for one of the Java projects, configured as Maven project,  only to realize that Maven builds failed after throwing this error. The main reason for this error is that Maven is not able to find javac (the Java compiler) which is required to compile Java source files. If you remember, the javac command comes in the bin directory of JDK, hence, you need a JDK installation in your local machine to compile the Java project.

How to fix java.sql.SQLException: Invalid column index? Example

"java.sql.SQLException: Invalid column index" is a frequent error while working in Java Database Connectivity (JDBC). As the name suggests "Invalid column index" its related to accessing or setting column in your SQL Query using prepared statement in Java. I have seen "java.sql.SQLException: Invalid column index" coming mostly due to two reason:

1) Setting column data using setXXXX(int coloumIndex) e.g. setInt(0) setString(0)
2) Getting column data using getXXX(int columnIndex) e.g. getInt(0) getString(0)

The most common cause of "java.sql.SQLException: Invalid column index" is a misconception that column index started with "0" like array or String index but that's not true instead column index starts with "1" so whenever you try to get or Set column data with column index "0" you will get "java.sql.SQLException: Invalid column index".

Friday, July 29, 2022

How to use ArrayList in Java? 10 Examples of ArrayList

ArrayList in Java is the most frequently used collection class after HashMap in Java. Java ArrayList represents an automatic re-sizeable array and used in place of the array. Since we can not modify the size of an array after creating it, we prefer to use ArrayList in Java which re-sizes itself automatically once it gets full. ArrayList in Java implements the List interface and allows null. Java ArrayList also maintains the insertion order of elements and allows duplicates opposite to any Set implementation which doesn't allow duplicates. ArrayList supports both the Iterator and ListIterator for iteration but it’s recommended to use ListIterator as it allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the Iterator's current position in the list.

Wednesday, July 27, 2022

How to find current directory in Java with Example

Hello guys, if you want to find current directory in Java and looking for a simple example then don't worry. Its easy to get current directory in Java by using built-in system property provided by Java environment. Current directory represent here the directory from where "java" command has launched. you can use "user.dir" system property to find current working directory in Java. This article is in continuation of my earlier post on Java e.g. How to load properties file in Java on XML format or How to parse XML files in Java using DOM parser and Why Java doesn’t support multiple inheritance . If you haven’t read them already, You may find them useful and worth reading. By the way here is a quick example of finding current directory in Java:

How to read from and write to a text file in Java - Example Tutorial

Java has excellent support for reading from file and writing to file in Java. In the last post, we have seen how to create files and directories in Java and now we will see how to read content from files in java and how we will write text into file in Java. File provides a persistent solution to Java developers; in almost every Java application you need to store some of the data in persistent may be its user configuration, system configuration or related to state of the application but without persistence, no enterprise Java application can buildup. 

How to append text into File in Java – FileWriter Example

As a Java developer we often need to append text into File in Java instead of creating a new File, for example log files where every message is written into same file or appended at the end of the file. Thankfully Java File API is very rich and it provides several ways to append text into File in Java. Previously we have seen how to create files and directories in Java and how to read and write to a text file in Java and in this Java IO tutorial we will see how to append text into files in Java. We are going to use the standard FileWriter and  BufferedWriter approach to append text to File. One of the key points to remember while using FileWriter in Java is to initialize FileWriter to append text i.e. writing bytes at the end of the File rather than writing at the beginning of the File.

How to Copy a File in Java Program - Example Tutorial

How to copy files in Java from one directory to another is a common requirement, given that there is no direct method in File API for copying files from one location to another. A painful way of copying files is reading from FileInputStream and writing the same data to FileOutputStream to another directory. Though this process works it's pretty raw to work with and the best approach is for anyone to create a library for common File operations like cut, copy, paste, etc. 

How to read File into String in Java 7, 8 with Example

Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write a lot of boilerplate code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on. Of course, JDK 1.5's Scanner class did provide some breathing space but it was still not as simple as it should be, like in Python or Ruby. By using Java 7 new File API and Java 8's new features like lambda expression and Stream API, Java is now close to Python or other utility languages, when it comes to reading the file into String.

Tuesday, July 26, 2022

Top 5 Free and Paid OCAJP, OCPJP Mock Exams and Practice questions - (Java Certification)

In order to do well on Java certifications, you need good books and a reasonable number of practice questions before you go for exams. Practice questions and mock exams will help you to assess your topic-wise preparation level and help you to identify your strong and weak areas. Based on the result of the mock exams, you can concentrate on areas where you lack expertise like multi-threading is one of the tricky areas. It will also expose you to exam patterns and different types of questions you can expect in examination like multiple choice questions, rearranging code, fill in the blanks etc. Though I highly recommend commercial exam simulators like Whizlabs and Enthuware, I also suggest you take advantage of many mock questions which are freely available.

Sunday, July 24, 2022

How to read a File in One Line in Java? Files.readAllLines() Example Tutorial

Reading a file in Java is not simple, it requires lots of boilerplate code, as we have seen in our earlier example of reading text files. Various things had to be wrapped e.g. a FileInputStream inside a BufferedReader, loops with weird terminating conditions had to be specified, and so forth. From JDK 7 onward,  you can do a lot better. It provides lots of useful classes like Files and Paths to deal with file and their actual path. In this article, we will see how we can read a file in just one line. Of course, your production code won't be like that, especially if you are reading a few gigabytes into memory and want to pay attention to the character set, if you don't specify, by platform's default character encoding will be used.

Java 8 - Stream FlatMap Example - List of Lists to List

The flatmap is an interesting concept of functional programming which allows you to flatten the list or stream apart from transforming it, just like the map does. This means you can use the flatmap to flatten the stream. If you have used the map() function from the Stream class before then you can use it to convert an object of type T to another object of Type S. For example, if you have a list of Authors then you can convert it to a List of books by transforming authors to books. FlatMap extends this idea, it not only transform one object to other it also flattens the list and that's it's very useful where you want to know about a combined data set. 

How to convert java.util.Date to java.sql.Date - JDBC Example

You often need to convert java.util.Date to java.sql.Date if you are storing dates in a database e.g. SQL SERVER or MySQL. Since JDBC has their own data types for date and time e.g. java.sql.Date, java.sql.Time and java.sql.TimeStamp to match with database date, time and date-time types, you cannot pass a java.util.Date directly. All methods which are supposed to store dates e.g. setDate(paramName, paramValue) expects java.sql.Date, so it becomes essential to know how to convert java.util.Date to java.sql.Date in JDBC. You would be surprised to know that java.sql.Date is a subclass of java.util.Date and all it does is suppress or remove time-related fields from java.util.Date.

Saturday, July 23, 2022

How to convert String to Date in Java - SimpleDateFormat Example

Hello Java developers, you may know that SimpleDateFormat in Java can be used to convert String to Date in Java. java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and can convert a particular String that follows that pattern into Date in Java. This is the second part of the article on java.util.Date and String in Java. In the first part, we have seen How to convert Date to String in Java. SimpleDateFormat accepts a String in any date format e.g. yyyyMMdd is a date pattern and  20220924 is a String in that format. Now you want to create a java.util.Date object from this String.

How to Convert Date to String in Java with Example

As a Java developer we often need to convert java.util.Date or LocalDate to String in Java for  displaying purpose or sending Date as String in JSON or XML messages and that's where having a agree upon Date Format is very important. It easily allows you to convert your Date as String and pass between two System. I need it that while working on displaying date in my application and then I thought about this article to list down various way of converting this in various ways after some reading I found that SimpleDateFormat makes this quite easy. 

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

The easiest way to convert a java.util.Date to java.time.LocalDate is via Instant, which is the equivalent class of java.util.Date in JDK 8. You can first convert util Date to Instant and then create a LocalDateTime object from that instant at your default timezone. Once you have an instant of LocalDateTime, you can easily convert that to LocalDate or LocalTime in Java. If you are not living under the rock in the last two years that its 2016 and Java 8 has been around for more than 2 years, 18th March 2014 Java SE 8 GA happened.

17 Examples of Calendar and Date in Java - Tutorial

The java.util.Calendar class was added in Java on JDK 1.4 in an attempt to fix some flaws of the java.util.Date class. It did make some tasks simpler, e.g. create an arbitrary date comes easier using the new GregorianCalendar(2016, Calendar.JUNE, 11) constructor, as opposed to the Date class where the year starts from 1900 and the Month was starting from zero. It didn't solve all the problems like mutability and thread-safety of Date class still remains, but it does make life easier at that time. Now with Java 8 everything related to Date and Time has become super easy and consistent but unfortunately, it will take another 5 to 10 years before the older version of Java goes away. Don't believe me, there are still applications running on JDK 1.5 which was released 12 years ago. The bottom line is it's still important to know about the Date and Calendar in Java.

Thursday, July 21, 2022

10 Difference between Java and JavaScript for Programmers

Programmers, developers, and internet users have always been confused between Java and JavaScript.  Many people still think that JavaScript is part of the Java platform, which is not true. In truth, JavaScript has nothing to do with Java, the only common thing between them is the word "Java", much like in Car and Carpet, or Grape and Grapefruit. JavaScript is a client-side scripting language for HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Microsystems. James Gosling is the Inventor of Java, popularly known as the father of Java. 

How to get current URL, parameters and Hash tag using jQuery and JavaScript? Example

While dealing with the current URL, many times you want to know what is the current URL path, What are the parameters, and what is the hashtag on the URL. The hashtag is pretty important if you are implementing a tab structure using HTML and JQuery. To avoid confusion, let's take an example of a URL: http://javarevisited.blogspot.com/2013/01/top-5-java-programming-books-best-good.html#ixzz2PGmDFlPd, in this example ixzz2PGmDFlPd, is a hashtag. Now, both JavaScript and JQuery provide a convenient way to retrieve the current URL in the form of window.location object. You can use various properties of the window.location JavaScript object like the window.location.href to get complete URL, window.location.pathname to get the current path, and window.location.hash to get a hashtag from current URL.

Monday, July 18, 2022

How to format/parse dates with LocalDateTime in Java 8 - Example Tutorial

One of the common tasks in a Java project is formatting or parsing data to String and vice-versa. Parsing date means you have a String that represents a date like "2017-08-3" and you want to convert it into an object which represents the date in Java, like java.util.Date in pre-Java 8 world and LocalDate or LocalDatetime in Java 8 world. Similarly, formatting a date means converting a date instance into a String, for example, you have a Date object or LocalDatetime object and you want a String in dd-MM-yyyy format. Java 8 API provides good support for formatting and parsing dates.

Difference between Period and Duration class in Java 8? [Example]

What is the difference between Period and Duration class in Java is one of the popular Java 8 interview questions and has been asked too many of my readers recently. If you were also wondering the difference between Period vs Duration and when to use Period over Duration and vice-versa then you have come to the right place. Java 8 has two classes to represent differences in time like Duration and Period. The main difference between Period and Duration is that they represent the difference in different units, A Duration is used to calculate time difference using time-based values (seconds, millisecond, or hours) but Period is used to measure the amount of time in date-based values like days, months and year.

Friday, July 15, 2022

What is Double Brace Initialization in Java? Example Initializing HashMap and List with values in Java

Double brace initialization is a Java idiom to initialize a Collection like a list, set, and map at the time of declaration. At times, you need a list of fixed elements e.g. supported products, supported currencies, or some other config, and on-the-spot initialization reduces the line of code and improves readability. Double brace initialization idiom becomes popular because there is no standard way to create and initialize Collection at the same time in Java. Unfortunately, unlike other JVM languages like Scala and Groovy, Java doesn't support collection literals yet. 

Thursday, July 7, 2022

Right way to Close InputStream and OutputStream in Java - Example

For some unknown reasons many Java programmers are not very comfortable with IO package. I don't know why, but I have found them much more comfortable with java.lang and java.util than java.io. One possible reason of this could be that, writing IO code require a bit of C++ like programming, which involves doing clean-up, releasing resources once done etc. Since Java made coding a lot easier by taking care of memory management, unknowingly it also introduced bad practice of not releasing resource after use like database connections, socket connection, files, directory, printers, scanners or any other scarce resource.

Wednesday, June 29, 2022

How to implement Command Design Pattern in Java with Example

Hello guys, it's been a long since I have shared a Java design pattern tutorial. I did share some courses to learn design patterns but haven't really talked about a particular design pattern in depth. So, today, we'll learn one of the important design pattern, which is often overlooked by Java developers. Yes, I am talking about the Command Pattern which can help you write flexible, loosely coupled code for implementing actions and events in your application. In simple words, the command design pattern is used to separate a request for action from the object which actually performs the action. This decoupling between Invoker and Receiver objects provides a uniform way to perform different types of actions. This decoupling is achieved using a Command object, which is usually an interface with methods like execute()

Monday, June 27, 2022

Can a Non Static Method Access a Static Variable/Method in Java?

"Can a non-static method access a static variable or call a static method" is one of the frequently asked questions on the static modifier in Java, the answer is, Yes, a non-static method can access a static variable or call a static method in Java. There is no problem with that because of static members i.e. both static variable and static methods belong to a class and can be called from anywhere, depending upon their access modifier. For example, if a static variable is private then it can only be accessed from the class itself, but you can access a public static variable from anywhere.

Sunday, June 26, 2022

How to create Tabs UI using HTML, CSS, jQuery, JSP and JavaScript? Example

JSP is still a popular technology for developing view part of Struts and Spring-based Java applications, but unfortunately, it doesn't have rich UI support available in GWT, or any other library. On another day, we had a requirement to display HTML tables inside tabs, basically, we had two tables of different data set and we need to display them in their own tabs. Users can navigate from one tab to another, and CSS should take care of which tab is currently selected, by highlighting the active tab. Like many Java developers, our hands-on HTML, CSS, and JavaScript are a little bit tight than a web guy, and since our application is not using any UI framework, we had to rely on JSP to do this job.

How to use Adapter Design Pattern in Java with Example

The adapter design pattern in Java, also known as the Wrapper pattern is another very useful GOF pattern, which helps to bridge the gap between two classes in Java. As per the list of Gang of Four patterns, the Adapter is a structural pattern, much like Proxy, Flyweight, Facade, and Decorator patterns in Java. As the name suggests, the Adapter allows two classes of a different interface to work together, without changing any code on either side. You can view the Adapter pattern as a central piece of the puzzle, which joins two pieces, which can not be directly joined because of different interfaces.

What is the Use of Interface in Java and Object Oriented Programming? [Answer]

Many times, I have seen questions like why should we use an interface in Java? If we can not define any concrete methods inside the interface the what is the user of the interface? Or even more common, What is the real use of the interface in Java? I can understand beginners asking this question when they just see the name of the method inside the interface and nothing else. It takes time to realize real goodness or actual use of interface or abstraction in Java or any object-oriented programming. One reason for this is a lack of experience in really modeling something real in the program using object-oriented analysis and design. In this article, I will try to answer this question and give you a couple of reasons to use the interface in your code. If you have a good understanding of Object-oriented basics like Polymorphism, then you know that it allows you to write flexible code.

Thursday, June 16, 2022

java.lang.UnsatisfiedLinkError: no dll in java.library.path - Cause and Solution

"Exception in thread "main" java.lang.UnsatisfiedLinkError: no dll in java.library.path" is one of the frustrating errors you will get if your application is using native libraries like the DLL in Windows or .SO files in Linux. Java loads native libraries at runtime from either PATH environment variable or location specified by java.library.path system property depending upon whether your Java program is using System.load() or java.lang.System.loadLibarray() method to load native libraries. If Java doesn't find them due to any reason it throws "java.lang.UnsatisfiedLinkError: no dll in java.library.path"

Spring Boot Error - Error creating a bean with name 'dataSource' defined in class path resource DataSourceAutoConfiguration

Hello guys, If you are using Spring Boot and getting errors like "Cannot determine embedded database driver class for database type NONE" or "Error creating a bean with name 'dataSource' defined in class path resource ataSourceAutoConfiguration" then you have come to the right place. In this article, we'll examine different scenarios on which this Spring Boot error comes and what you can do to solve them. The general reason for this error is Spring Boot's auto-configuration, which is trying to automatically configure a DataSource for you but doesn't have enough information. It is automatically trying to create an instance of DataSourceAutoConfiguration bean and it's failing.

Difference between WHERE vs HAVING clause in SQL - GROUP BY Comparison with Example

What is the difference between WHERE and  HAVING clause in SQL is one of the most popular questions asked on SQL and database interviews, especially to beginners? Since programming jobs, required more than one skill, it’s quite common to see a couple of SQL Interview questions in Java and .NET interviews. By the way unlike any other question, not many Java programmers or dot net developers, who are supposed to have knowledge of basic SQL, fail to answer this question. Though almost half of the programmer says that WHERE is used in any SELECT query, while HAVING clause is only used in SELECT queries, which contains aggregate function or group by clause, which is correct.

Wednesday, May 25, 2022

How to Set Classpath for Java on Windows and Linux? Steps and Example

What is CLASSPATH in Java? Classpath in Java is the path to the directory or list of the directory which is used by ClassLoaders to find and load classes in the Java program. Classpath can be specified using CLASSPATH environment variable which is case insensitive, -cp or -classpath command-line option or Class-Path attribute in manifest.mf file inside the JAR file in Java.  In this Java tutorial, we will learn What is Classpath in Java, how Java resolves classpath and how Classpath works in Java alongside How to set the classpath for Java in Windows and UNIX environment. 

Monday, May 23, 2022

Difference between Direct, Non Direct and Mapped ByteBuffer in Java?

ByteBuffer is one of the important classes of Java NIO API. It was introduced in java.nio package on JDK 1.4, it not only allows you to operate on heap byte arrays but also with direct memory, which resides outside the JVM. There are mainly three types of ByteBuffer in Java - Direct Byte Buffer, Non-Direct ByteBuffer, and mapped byte buffers. You can create both direct and non-direct buffers using java.nio.ByteBuffer class, while MappedByteBuffer is a subclass of ByteBuffer, which is created by FileChannel.map() method, to operate on memory-mapped file

Wednesday, May 11, 2022

String vs StringBuffer vs StringBuilder in Java? Example

Difference between String, StringBuffer, and StringBuilder
The String is one of the most important classes in Java and anyone who starts with Java programming uses String to print something on the console by using famous System.out.println() statements. Many Java beginners are not aware that String is immutable and final in Java and every modification in String creates a new String object. For example, when you get the substring, you get a new String, when you convert uppercase String to lowercase, a new String is created. Even when you remove space by calling the trim() method, a new String is returned. 

Sunday, May 8, 2022

Java 8 forEach() Loop Example

Java 8 has introduced a new way to loop over a List or Collection, by using the forEach() method of the new Stream class. You can iterate over any Collection like List, Set, or Map by converting them into a java.util.sttream.Stream instance and then calling the forEach() method. This method performs given operation on every element of Stream, which can be either simply printing it or doing something else. Since stream can be sequential or parallel, the behavior of if this method is not deterministic if used with a parallel stream

Difference between Transient, Persistent, and Detached Objects in Hibernate

In the Hibernate framework, an entity can be in three states, transient, persistent, and detached. When an object is in a transient state, it is commonly referred to as a transient object, similarly, if it is in persistence and detached state, it is known as a persistent and detached object. When an entity is first created using the new operator like new User() and not associated with Hibernate session like you haven't called session.save(user) method then it is known as a transient object. At this stage, Hibernate doesn't know anything about this object and the object doesn't have any representation in the database like a corresponding row in the User table.

Wednesday, April 27, 2022

How to use filter + map + collect + Stream in Java? Example Tutorial

Hello guys, many of my readers emailed me to write a post about the map and filter function of Java 8 because they found it difficult to understand and use. Even though I have previously blogged about both map() and filter(), I am writing this post again to explain the concept in more layman's language for a better understanding of my readers and fellow Java developers. The map() function is a method in Stream class that represents a functional programming concept. In simple words, the map() is used to transform one object into another by applying a function. That's the reason the Stream.map(Function mapper) takes a function as an argument. For example, by using map() function, you can convert a list of String into List of Integer by applying Integer.valueOf() method to each String on the input list.

Wednesday, April 20, 2022

Top 50 SQL and Database Phone Interview Questions Answers

Database and SQL is a very important skill, not just for DBA or Database admins but also for any application developer like Java.NET, or Web developers. This is why you would often see questions from SQL and Database in Programming interviews. For DBAs, SQL is more important than a programmer, because it being their primary skill, they are also expected to know more than a common Java or .NET developer. Since no Java interview is just about Java questions, many times I receive a request from my reader about SQL questions like how to solve a particular query or some tricky questions based upon database indexes.

Monday, April 18, 2022

How to use Environment Variables in Spring Boot's application.properties file? Example Tutorial

How to use environment variable in Spring boot's application.properties is a major problem when your spring boot application running on different places like local, Jenkins, and OpenShift. So we need to make the data source file dynamic in the application.properties file. So let's have look at how to do this at how to use the env variable in Spring Boot's application.properties. So in this tutorial, We assume that you have knowledge of Spring boot and not going to talk about small details. 

Thursday, April 7, 2022

How to Create a thread-safe ConcurrentHashSet in Java 8? [Example]

Until JDK 8, there was no way to create a large, thread-safe, ConcurrentHashSet in Java. The java.util.concurrent package doesn't even have a class called ConcurrentHashSet, but from JDK 8 onwards, you can use the newly added keySet(default value) and newKeySet() methods to create a ConcurrentHashSet backed by ConcurrentHashMap in Java. This is better than old tactical solutions like using a concurrent hash map with dummy value or using the set view of the map, where you cannot add new elements. The Set returned by keySet(defaultValue) and newKeySet() methods of JDK 8 is a proper set, where you can also add new elements along with performing other set operations like contains(), remove() etc.

Wednesday, March 30, 2022

How to Read JSON String in Java using json-simple library? Example Tutorial

Hello guys, if you are wondering how to read JSON in Java using the json-simple library and looking for an example then you have come to the right place. Earlier, I have shown you how to parse JSON using Jackson and how to read JSON using the Gson library in Java, and today, I am going to share how to read JSON strings using json-simple, another popular JSON library in Java. If you don't know, JSON is a text format that is widely used as a data-interchange language because its parsing and its generation are easy for programs. It is slowly replacing XML as the most powerful data interchange format, as it is lightweight, consumes less bandwidth, and is also platform-independent.  

Saturday, March 26, 2022

How to send JSON via POST request using RestTemplate in Spring | PostForObject, PostForEntity, and PostLocation Example in Java

Hello guys, if you are wondering how to send a Post request with Json in Java application using Spring framework then you have come to the right place. Earlier, I have shown how to consume JSON from a RESTful API and In this tutorial, we are going to discuss how to send POST requests via RestTemplate in JSON. We will have an example project which is having POST API and then test it by sending request body along with request headers using postEntry(). POST requests can be made using the RestTemplate class's postForObject(), postForEntity(), and postForLocation() template methods. The first two techniques are fairly similar to what I covered in the GET request lesson for RestTemplate. Instead of returning the whole resource, the last method returns the location of the newly formed resource.

Wednesday, March 16, 2022

Spring Boot + Redis Example in Java

Hello guys, if you are wondering how to use Redis with Spring Boot in Java then you have come to the right place. Earlier, I have shared the Spring Boot + React example, Spring Boot + Angular example, and Spring Boot + MyBatis examples In this tutorial, we will review the basics of how to use Redis with Spring Boot. We will build an application that demonstrates how to perform CRUD operations Redis through a web interface. So before going into in detailed project example, let's move with the what is spring Redis. As Java developers, we need to talk about the data layer, as we can't develop an insightful application without the use of CRUD operations. 

Saturday, February 12, 2022

How to delete a key value pair from a HashMap during Iteration in Java - Example tutorial

Suppose you have a Map or Dictionaries like HashMap or Hashtable, which contains key-value pairs like books and their prices, and you want to delete all books whose prices are greater than 40 USD, how do you that in Java? This is one of the most common scenarios while developing Java applications and many Java programmers, will say that they will iterate over Map and check each entry and then use the remove(Object key) or remove(Object key, Object value) methods from java.util.Map to delete any mapping where the value is greater than 40 USD. Though the approach is right, the answer is wrong.

Thursday, February 10, 2022

Top 30 Java Phone Interview Questions Answers for Freshers, 1 to 2 Years Experienced

Hello guys and ladies, in this article, I am sharing 30 core Java technical questions, from screening and phone rounds of interviews. In telephonic interviews, questions are short, fact-based and Interviewer expects a to-the-point reply and some keywords in answers. Accordingly, I have given very short answers to all these questions, only the main points; just to make this a revision post and not the main source for preparation. For thorough preparation, my master list of 140+ Java questions is a better one to start with. I am also expecting every Java programmer to know answers to all these Java technical questions if he has more than 4 to 5 years of experience. It's only freshers and junior developers who need to do a bit of research to understand topics well.

5 Benefits of using interface in Java and Object Oriented Programming

Interface in Java is a simple concept but many programmers fail to realize their actual use, including me. When I started learning Java programming, I learned interface is something where you can declare functions but cannot define them. To me, they were useless at that time because there was no code to do anything. It took me years to realize how useful an interface can be. They are not intended to do things but they are actually facilitators. They provide abstraction and give the flexibility to change your program in the future. That's why it's very important for a Java programmer to understand the benefits of interfaces and realize how and when to use them in code. 

Tuesday, February 8, 2022

Difference between SOAP and RESTful Web Service in Java

Though both SOAP and RESTful web services allow a client to query the server for some information, the way they are implemented and used is quite different. The main difference between SOAP and REST is that the former provides a standard of communication between client, server, and other parties and has restricted a set of rules and format, while REST leverages the ubiquity of HTTP protocol, in both client and servers, to allow them to communicate with each other regardless of their implementation. In short, getting data from a RESTful web service requires less headache than getting data from a SOAP web service.

3 Ways to Read File line by line in Java 8? Examples

Java 8 has added a new method called lines() in the Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed. So, if you have a huge file and you only read the first 100 lines then the rest of the lines will not be loaded into memory, which results in better performance. This is slightly different from the Files.readAllLines() method (which reads all lines into a List) because this method reads the file lazily, only when a terminal operation is called on Stream like forEach(), count(), etc. By using the count() method you can actually count a number of lines in files or the number of empty lines by filtering empty lines.

Sunday, February 6, 2022

2 Examples to read Zip Files in Java, ZipFile vs ZipInputStream - Tutorial

ZIP format is one of the most popular compression mechanisms in the computer world. A Zip file may contain multiple files or folders in compressed format.  Java API provides extensive support to read Zip files, all classes related to zip file processing are located in the java.util.zip package. One of the most common tasks related to zip archive is to read a Zip file and display what entries it contains, and then extract them in a folder. In this tutorial, we will learn how to do this task in Java. There are two ways you can iterate over all items in a given zip archive, you can use either java.util.zip.ZipFile or java.util.zip.ZipInputStream. Since a Zip file contains several items, each of them has a header field containing the size of items in a number of bytes. This means you can iterate all entries without actually decompressing the zip file.

Friday, February 4, 2022

How to access Private Field and Method Using Reflection in Java? Example Tutorial

Reflection in Java is a very powerful feature and allows you to access private methods and fields which is not possible by any other means in Java and because of this feature of reflection many code coverage tools, static analysis tools,s and Java IDE like Eclipse and Netbeans has been so helpful. In the last article, we have seen details about private keywords in Java and learned why we should always make fields and methods private in Java. There we have mentioned that private fields and methods are only accessible in the class they are declared but with reflection, you can call the private method and access private fields outside the class. In this article, we will see a simple example of accessing a private field using reflection and invoking a private method using reflection in Java.

Monday, January 31, 2022

How Garbage Collection works in Java? Explained

I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article. You can call it a tutorial about garbage collection in simple words, which would be easy to understand and have sufficient information to understand how garbage collection works in Java. Garbage collection works by employing several GC algorithms like Mark and Sweep, G1, etc. There are different kinds of garbage collectors available in Java to collect different areas of heap memory like you have serial, parallel, and concurrent garbage collectors in Java.

Sunday, January 16, 2022

Top 30 JavaScript Interview Questions with Answers for 1 to 5 Years Experienced Programmers

Building a career as a developer in the IT industry can be challenging if you lack stream-specific preparation. For instance, if you want to be a JavaScript developer, you have to dig deep into its concepts and learn every bit about JavaScript, but then also, I would say, you are 50% prepared for the Job. I'm not saying that you aren't capable enough to get that JavaScript developer's Job; instead, I mean to say that you aren't ready enough to face the recruiters.