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.

Monday, November 28, 2022

3 ways to convert String to Boolean in Java? Examples

Hello guys, if you ar wondering how to convert a String object to boolean value in Java then don't sweat there are multiple ways to convert a String to Boolean class or boolean value in Java. For Example, ou can convert a String object to a Boolean object or boolean primitive by using the Boolean.valueOf() and Boolean.parseBoolean() method. The steps are similar rot converting to String to other data types  like String to Integer and String to Long. You can use the valueOf() method to convert String to Boolean object and parseBoolean() method to convert a given string to a boolean primitive value. Internally, valueOf() also uses parseBoolean() for parsing String but on top of that it also provides caching e.g. it can return Boolean.TRUE and Boolean.FALSE cached value for "true" and "false" strings. 

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

FIX Session is not connecting how to diagnose it? Example Tutorial

In this blog post of the FIX protocol tutorial series I would like to share my experience with connectivity issues around Fix Engines. to exchange messages or say to trade electronically clients connect to the broker using FIX protocol and for that, they use FIX Engine. In FIX protocol connection between two FIX Engines is refereed as FIX Session and we normally say whether FIX Session is connected or not connected. FIX Session normally has their start time, end time, and EOD time (End of day time) also called TradingSession start time, Trading Session End Time, and Trading Session EOD time.

Saturday, July 30, 2022

10 Free Web Development Courses for Beginners in 2024 - Best of Lot

Hello guys, if you want to learn Web Development in 2024 and looking for best free resources like free online courses, tutorials, and books then you have come to the right place. Earlier, I have shared best online courses to learn HTML, CSS, JavaScript, React, Angular, and Node.js and in this article, I am going to share best free online courses to learn Web Development. The article includes free web-dev courses from sites like Udemy and Coursera which anyone can join free to learn essential Web development skills in 2024. But, Before we get to the 7 best free courses that will teach you everything you need to know about web development, let me tell you what it really is.

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.

Top 10 Free Spring Boot and Spring Framework Courses in 2024 - Best of Lot

Hello guys, if you want to learn Spring Framework and Spring Boot in 2024 and looking for free resources like free online courses, tutorials, and books then you have come to the right place. Earlier, I have shared best online courses to learn Spring Framework, Spring MVCSpring Boot, Spring Security, Spring Data JPA, and Reactive Spring/WebFlux and in this article, I Am going to share best free online courses to learn Spring Framework and Spring boot in depth. But, Before we get to the 10 best free Spring courses that are perfect for beginners, let me tell you more about what the Spring Framework really is.

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.

Tuesday, July 19, 2022

Top 10 Free NFT (Non Fungible Tokens) Courses for Beginners in 2024 - Best of Lot

Hello guys, if you want to learn about NFTs or Non Fungible Tokens and looking for best free online courses then you have come to the right place. Earlier, I have shared best paid NFT courses and in this article, I am going to share best free NFT courses for beginners, Bu, before we get to the 10 best free NFT courses that will teach you everything you need to know about this exciting new technology, let me tell you what it really is. NFTs, also known as Non-Fungible Tokens, are basically unique cryptographic tokens. These tokens exist in a blockchain, which means that they cannot be replicated. Each NFT has a unique identification and metadata. 

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, July 6, 2022

Top 15 Java String interview Question Answers for 3 to 5 Years Experienced

10 Java String interviews Question answers
String interview questions in Java is one of Integral part of any Core Java or J2EE interviews. No one can deny the importance of String and how much it is used in any Java application irrespective of whether it's core Java desktop application, web application, Enterprise application or Mobile application. The string is one of the fundamentals of Java programming language and correct understanding of String class is a must for every Java programmer. What makes String interview questions in Java even more interesting is the special status of String in terms of features and privileges it has like the + operator is kind of overloaded to perform String concatenation despite the fact that Java does not support operator overloading. There is a separate String pool to store String literal etc.

How to compare two String in Java - String Comparison Example

String comparison is a common programming task and Java provides several way to compare two String in Java. String is a special class in Java, String is immutable and It’s used a lot in every single Java program starting from simple test to enterprise Java application. In this Java String compare tutorial we will see different ways to compare two String in Java and find out how they compare String and when to use equals() or compareTo() for comparison etc.

Here are four examples of comparing String in Java
1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method

Which is the best course to Learn Spring Security 5 and Spring Data JPA for Java Programmers?

If you are a Java Spring developer and working with Spring Security then you may be familiar with the "Learn Spring Security" course by Eugen Paraschiv of Baeldung. It is one of the most advanced and comprehensive courses on Spring Security and the best part of this course is that Eugen always keeps it up-to-date with the new Spring Security release. Now that version Spring Security 5 is out - he has updated his course to use new features of Spring Security 5. Btw, there is some really cool new functionality coming in Spring Security 5 for the reactive programming model, and many other improvements and new features. But, the most important one is the release of OAuth2.

Saturday, July 2, 2022

How to Remove First and Last Character of String in Java - Example Tutorial

You can use the substring() method of java.lang.String class to remove the first or last character of String in Java. The substring() method is overloaded and provides a couple of versions that allows you to remove a character from any position in Java. Alternatively, you can convert String to StringBuffer or StringBuilder and then use its remove() method to remove the first or last character. Both StringBuffer and StringBuilder provides a convenient deleteCharAt(int index) method which removes a character from the corresponding index. You can use this method to remove both first and last characters from String in Java.

How to get first and last character of String in Java - Example

You can get the first and last character of a String using the charAt() method in Java. This method accepts an integer index and returns the corresponding character from String. Since Java String is backed by an array, their index is also zero-based, which means the first character resides at index zero, and the last character is at index, length-1, where length is the number of characters in the String. You can get the length of the String by calling the length() method. The charAt() method is not defined on java.lang.String class, but on its super interface java.lang.CharSequence, hence it will also work for StringBuffer and StringBuilder.

How to check if String is not null and empty in Java? Example

In Java, since null and empty are two different concepts, it's a little bit tricky for beginners to check if a String is both not null and not empty. A String reference variable points to null if it has not been initialized and an empty String is a String without any character or a string of zero length. Remember, a String with just whitespace may not be considered as empty String by one program but considered as empty String by others, so, depending upon your situation, you can include the logic to check for that as well. A String with just white space is also referred to as a blank String in java. In this tutorial, I will teach you a couple of right ways to test if a String is not null and not empty in Java.

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()

How to sort an Array in Java? Ascending and Descending Order Example

As a Java programmer, quite often you would need to sort array in Java luckily java.util.Arrays class provides several utility methods to sort an array in Java. You can sort different types of array in Java like array of primitive data types, object or int, String, etc. Arrays are in java.util package and exposed all sorting related methods as static utility functions. you can access sort() as Arrays.sort() and just pass your array and it will sort that array object by comparing them in the order implemented in the compareTo() method if the class implements Comparable interface. You can also sort arrays in ascending order, descending order, or any custom order defined by the custom comparator in Java.

How to loop through an Array in Java? Example Tutorial

Hello there, If you want to loop over an array in Java but not sure how to do that then you have come to the right place. Earlier, I have shared many Java array tutorials and the best Java courses for beginners, and today, I am going to teach you how to iterate over an array in Java. There are multiple ways to loop over an array in Java, like you can use a for loop, an enhanced for loop, a while loop, or a do-while loop. Since while and do-while needs a condition to terminate they often depend upon the content of the array like stop when the current element is null or even or odd etc. If you just want to iterate over an array to access each element like loop over an array and print each entry then you should use either for loop or the enhanced for loop.

How to declare and initialize a List with values in Java (ArrayList/LinkedList) - Arrays.asList() Example

Hello guys, today, I am going to share with you a useful tip to initialize a List like ArrayList or LinkedList with values, which will help you a lot while writing unit tests and prototypes. Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs like the collection literals of Scala, but there is a trick which you can use to declare and initialize a List at the same time. This trick is also known as initializing a List with values. I have used this trick a lot while declaring list for unit testing and writing demo programs to understand an API etc and today I'll you'll also learn that.

Tuesday, June 28, 2022

How to implement Skip List in Java? Example Tutorial

Hello friends, we meet again today. hope you all are excited and ready for today's journey. Today, we are gonna learn something that is not very common. It is used not very common, but, if used, it is a great strength to our time complexity reduction. So, what's the wait? Let's start! So, suppose we have a linked list with us which has 10 million records. Now, for searching a particular node, the time taken would be O(N). Where N is the size of the list. Similarly, the time taken for deletion of a Node, Insertion at a particular Node will also take O(N) time. Can we reduce it?

Monday, June 27, 2022

Top 5 Websites to Learn Java Coding for FREE - Best of lot

Hello guys, if you want to learn Java Programming and looking for the best websites to learn Java coding for free then you have come to the right place. In the past, I have shared the best Java courses and books, today, I am going to share free websites to learn Java Programming for free. being the author of a Java blog and programmer I often receive questions like how to improve my coding skills?,  or how do I learn to code in Java?, or I am having difficulty solving programming problems, please help, etc. This is mostly from programmers who have just started programming or computer science graduates with a programming degree or even some programmers with a year or two in Job.

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 find If Linked List Contains Loop or Cycle in Java? Example Solution

Write a Java program to check if a linked list is circular or cyclic,  and how do you find if a linked list contains loop or cycles in Java are some common linked list related data structure interview questions asked in various Java Interviews. This is sometimes asked as a follow-up question of basic linked list questions like inserting an element at the beginning, middle and end of a linked list or finding the length of linked list. In order to solve linked list related algorithmic questions in Java, you need to be familiar with the concept of singly linked list, doubly linked list, and circular linked list. Until stated specifically, most questions are based on a singly linked list. For those who are not familiar with the linked list data structure, its a collection of nodes.

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.

Top 5 books to Learn Object Oriented Programming and Design - Must Read, Best of Lot

The OOP or Object Oriented Programming is one of the most popular programming paradigms which helps you to organize code in the real-world system. It's a tool that allows you to write sophisticated software by thinking in terms of objects and relationships. Unlike its predecessor procedural Programming paradigm, which is implemented most notably by C, which solves the problem and complete task by writing code for computers, the OOP style of programming allows you to think in terms of real-world objects which have both state and behavior. You can view anything as objects and then find their state and behaviors, this will help you to simulate that object in code.

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.

Saturday, June 25, 2022

Difference between Inheritance and Composition in Java and Object Oriented Programming

Though both Inheritance and Composition provide code reusability, the main difference between Composition and Inheritance in Java is that Composition allows reuse of code without extending it but for Inheritance, you must extend the class for any reuse of code or functionality. Another difference that comes from this fact is that by using Composition you can reuse code for even the final class which is not extensible but Inheritance cannot reuse code in such cases. Also by using Composition, you can reuse code from many classes as they are declared as just a member variable, but with Inheritance, you can reuse code from just one class because in Java you can only extend one class because multiple Inheritance is not supported in Java.

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, June 1, 2022

How to Design Vending Machine in Java - Part 2 [Object Oriented Design Problem with Solution]

This is the second part of the Java tutorial to show how to design Vending Machine in Java. In the first part, we have discussed the problem statement and the solution itself, but unit testing and design document were still pending, which we'll see in this article.  As I said, there are multiple ways to design a Vending machine in Java, for example, you could have easily used state design patterns to implement a vending machine, in fact, it's one of the best examples of State design patterns. Vending machine behaves differently in different states like return a product if the machine is not empty, otherwise, it just returns coins, so it ideally fits in the state design pattern.

Wednesday, May 25, 2022

Top 5 Cloud Computing Platforms Java Programmers Should Know

Cloud computing is Hot, it's the biggest IT trend of the last few years and will continue to grow strong in the coming future. Cloud computing provides several not-so-easy-to-ignore advantages, especially to public and small enterprises, which cannot afford to own and maintain expensive data centers. Since most online businesses nowadays need high availability, scalability, and resiliency, with-in a quick time, it's not possible to achieve all these on your own, and cloud computing becomes the best alternative here. Cloud service providers like Amazon Web Services (AWS) has helped several firms to remain focus on their business, without worrying for IT and infrastructure too much, this has yield big result for them.

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.