5 ways to add multiple JAR in to Classpath in Java - Examples

How to add the JAR file to Classpath in Java
Adding JAR into classpath is a common task for Java programmers and different programmers do it in different ways. Since Java allows multiple ways to include JAR files in the classpath, it becomes important to know the pros and cons of each approach and How exactly they work. There are 5 ways to add jars into classpath in Java some of them we have already seen in  How classpath works in Java and How to set Path in JavaIn this post, we will revisit some of those techniques and explore Java 1.6 wildcard to add multiple JAR into the classpath. 

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. 

How to implement Post Order Traversal of Binary Tree in Java - Recursion and Iteration Example

This is the third article on tree traversal. In the last couple of articles, I have shown you how to implement preorder and inorder traversal in Java, both recursively and iteratively and today, you will learn about the post-order traversal. Out of these three main tree traversal algorithms, the post-order traversal is most difficult to implement, especially the iterative version. In postorder traversal, you first visit left subtree, then right subtree and at last you print the value of root or not. So, the value of root is always printed at last in the post-order traversal.

Java Enum Tutorial: 10 Examples of Enum in Java

What is Enum in Java
Enum in Java is a keyword, a feature that is used to represent a fixed number of well-known values in Java, For example, Number of days in the Week, Number of planets in the Solar system, etc. Enumeration (Enum) in Java was introduced in JDK 1.5 and it is one of my favorite features of J2SE 5 among Autoboxing and unboxing, Generics, varargs, and static import. One of the common use of Enum which emerged in recent years is Using Enum to write Singleton in Java, which is by far the easiest way to implement Singleton and handles several issues related to thread-safety and Serialization automatically. 

Top 10 Excuses Programmers Gives to Avoid Unit Testing

Though everyone loves unit tests and everyone agrees with the benefits they bring in, when the time comes to write them, you will see a lot of excuses, even from some of the more experienced and senior developers. At the heart of the problem of not writing unit tests or enough unit tests are two things, first is time pressure i.e. you don't have enough time to complete coding forget about writing unit tests. This problem comes due to erroneous estimation i.e. only estimating time for coding and not including unit testing as part of development.

How to Solve java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener in Spring? [Example]

If you have worked in Spring MVC then you may be familiar with  
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
which is common problem during deployment. Spring MVC throws  java.lang.ClassNotFoundException:                           org.springframework.web.context.ContextLoaderListener ,
when its not able to find org.springframework.web.context.ContextLoaderListener class which is used to load spring MVC configuration files like application-context.xml and other Spring Framework configuration files defined in context-param element of web.xml in an Spring MVC web application as:

How to Print Pyramid Pattern of Characters in Java - Example Tutorial

In earlier programming tutorials, I have taught you how to print a pyramid pattern of stars and numbers in Java, and in this tutorial, you will learn the printing pyramid patterns of alphabets. If you understand the logic of previous programs then this one won't be difficult for you because we will use the same logic of printing rows and columns using the nested loop in Java. Actually, a pyramid pattern is nothing but a matrix where you need to print rows and columns. Though, you need to learn where to print those values and when to move to the next row.

How to use var to declare local variables in Java? Example Tutorial

Hello guys, In this series of new features of Java 10 articles, today, I am going to talk about probably the most popular and most useful, the introduction of var keyword (well, it's not really a keyword but I'll you later about it) in Java. If I am not wrong, this feature was supposed to come on Java 9 but dropped later. Finally, Java also has a var keyword to declare variables which allows you to declare a variable without their type e.g. instead of doing String str = "Java" you can now just say var str = "Java". This may not sound much gain when declaring String or an int variable but consider complex types with generics, this will surely save a lot of typing and also improves the readability of code.

How to Implement Binary Search Tree in Java? Example

A binary search tree or BST is a popular data structure that is used to keep elements in order. A binary search tree is a binary tree where the value of a left child is less than or equal to the parent node and the value of the right child is greater than or equal to the parent node. Since it's a binary tree, it can only have 0, 1, or two children. What makes a binary search tree special is its ability to reduce the time complexity of fundamental operations like add, remove, and search, also known as insert, delete and find. In a BST, all these operations (insert, remove, and find) can be performed in O(log(n)) time.

What is @SuppressWarnings annotation in Java? Unchecked, RawTypes, Serial Example

@SuppressWarnings annotation is one of the three built-in annotations available in JDK and added alongside @Override and @Deprecated in Java 1.5. @SuppressWarnings instruct the compiler to ignore or suppress, specified compiler warning in annotated element and all program elements inside that element. For example, if a class is annotated to suppress a particular warning, then a warning generated in a method inside that class will also be separated. You might have seen @SuppressWarnings("unchecked") and @SuppressWarnings("serial"), two of most popular examples of @SuppressWarnings annotation. Former is used to suppress warning generated due to unchecked casting while the later warning is used to remind about adding SerialVersionUID in a Serializable class.

Coursera Review - Full Stack Web Development with Angular Specialization Is it worth it?

Hello guys, if you are looking for the best Cousrser course to learn Angular or want to know whether the Full Stack Web Development with Angular Specialization on Coursera is worth your time and money or not, then you have come to the right place. Earlier, I have shared the best web development courses from Coursera, and in this article, I will review the most popular Angular course - Full Stack Web Development with Angular Specialization. This is one of the best Coursera specializations for Angular, and it contains 3 courses to learn Bootstrap, Angular, and Node.js to become a complete full-stack developer using JavaScript. 

How to Base 64 Encoding Decoding in Java 8 - Example Tutorial

Until Java 8, there was no standard way to Base64 encode a String in Java or decode a base64 encoded String. Java Programmers either use Apache Commons library and its Base64 class to encode or decode binary data into base 64 encoding, as shown here, or rely on internal Sun classes e.g. sun.misc.BASE64Encoder and sun.misc.BASE64Decoder(), which was not officially part of JDK and can be removed without notification. Java 8 solves this problem by providing standard support for base64 encoding and decoding by providing a java.util.Base64 class. 

Difference between Process and Thread in Java - Example

One of the common questions from programming interviews is, what is the difference between a Thread and a Process? Well, the main difference between them is that a Process is a program that is executing some code and a thread is an independent path of execution in the process. A process can have more than one thread for doing independent tasks e.g. a thread for reading data from disk, a thread for processing that data, and another thread for sending that data over the network. This technique to improve throughput and better utilize CPU power is also known as multi-threading.

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

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. Key in hashmap is just an add-on to find values, so you can just pick the values from Map and create a List out of it. The map in Java allows duplicate values which is fine with List which also allows duplicates but Map doesn't allow duplicate keys.

Spring @Transactional Annotation Example - How to Manage Transaction using Spring Framework?

One of the most essential parts of Spring MVC is the @Transactional annotation, which provides broad support for transaction management and allows developers to concentrate on business logic rather than worrying about data integrity in the event of system failures. Spring Framework provides declarative and programmatic transaction management, and developers can choose between convenience and control, depending on the requirement. Declarative transaction management is easier and suitable in most cases, but in some cases, you want fine-grain control, and you can use the declarative transaction. We'll see examples of both declarative and programmatic transaction management in this article. 

How to create thread safe Singleton in Java - Java Singleton Example

Thread safe Singleton means a Singleton class that returns exactly the same instance even if exposed to multiple threads. Singleton in Java has been a classical design pattern like Factory method pattern, or Decorator design pattern and has been used a lot even inside JDK like java.lang.Runtime is an example of Singleton class. Singleton pattern ensures that exactly one instance of the class will remain in the Java program at any time. In our last post, 10 Interview questions on Singleton in Java we have discussed many different questions asked on Singleton pattern, One of them was writing Thread safe singleton in Java.

How to Code in Dart Programing language? Dart Hello World Example Tutorial

Google Datt is a general-purpose programming language from Google and is used to build web applications, mobile applications, and the Internet of Things (IoT).  Its most popular application is in Flutter framework, which is Google's mobile app SDK for crafting high-quality native interfaces on iOS and Android in record time. If you haven't tried it yet then it's a good time to try it and see how much it offers to a programmer and whether it is a suitable language to replace JavaScript or not. 

How to Map a Network Drive to Windows Machine - net use Command Example

Mapping network drive in Windows 10 or other versions of Windows operating system e.g. Windows 7  or Windows 8 is much easier and faster by using the command line than by doing it on Windows Explorer. If you have been working in a Windows environment with a bunch of Windows Server 2016 or 2012  servers and your job requires frequent access, copy or paste from the local machine to those remote machines then mapping them as a network drive is the best option. 

Inner class and nested Static Class in Java with Example

Inner class and nested static class in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non-static nested classes are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular questions is the difference between inner class and nested static class , some time also referred to as a difference between static and non static nested class in Java. One of the most important questions related to nested classes are Where should you use nested class in Java?

How to Attach Source Code in Eclipse to JAR Files for Debugging and Navigation With JDK Example

Attaching the source of any Jar in Eclipse e.g. JDK or open-source libraries like Spring framework is a good idea because it helps during debugging and code development. As a Java programmer at least you should attach the source of JDK in Eclipse IDE to find out more about JDK classes. Though Eclipse IDE is pretty good on code assist, sometimes You want to know what's going inside a library or a JDK method, rather than just reading the documentation. Interview questions like How HashMap works in Java or How substring causes memory leak can only be answered if you are familiar with the source code of these classes.  

How to Compare Arrays in Java – Equals vs deepEquals Example

java.util.Arrays class provides equals() and deepEquals() method to compare two Arrays in Java. Both of these are overloaded methods to compare primitive arrays e.g. int, long, float, double, and Object arrays e.g. Arrays.equals(Object[], Object[]). Arrays.equals() returns true if both Arrays which it is comparing are null If both arrays pointing to the same Array Object or they must be of the same length and contains the same element in each index. In all other cases, it returns false. Arrays.equals() calls equals() method of each Object while comparing Object arrays.

How to append text into File in Java – FileWriter Example

Sometimes we need to append text into File in Java instead of creating a new 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.

4 Example to Iterate over HashMap, Hashtable or any Map 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 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. 

Top 5 Courses to learn Unreal Engine in 2021 - Best of Lot

Hello guys, if you are interested in game development then you may have heard about the Unreal engine, a popular engine to create games in C++. The Unreal Engine is open-source software that allows developers to make video games without even the need to be good at programming or even a programmer with some pre-made games such as a first-person shooter where you can edit it and not starting from scratch. If you want to learn Unreal Engine and looking for the best online courses and tutorials then you have come to the right place.

How to add, subtract days, months, years, hours from Date and Time in Java - Example

Adding days, hours, month or years to dates is a common task in Java. java.util.Calendar can be used to perform Date and Time arithmetic in Java. Calendar class not only provides date manipulation but it also support time manipulation i.e. you can add, subtract hours, minutes and seconds from current time. Calendar class automatically handles date transition or month transition for example if you ask date after 30 days it will return you date based on whether current month is 30 or 31 days long. Same is true in case of adding and subtracting years, Calendar takes care whether current or following year is a leap year or not.

Difference between equals method and "==" operator in Java - Interview Question

Both equals() and "==" operators in Java are used to compare objects to check equality but the main difference between the equals method and the == operator is that the former is a method and the latter is an operator. Since Java doesn’t support operator overloading, == behaves identical for every object but equals() is a method, which can be overridden in Java, and logic to compare objects can be changed based upon business rules. Another notable difference between the == and equals method is that the former is used to compare both primitive and objects while the latter is only used for objects comparison.

What is final in Java? Final variable , Method and Class Example

Final in Java is very important keyword and can be applied to class, method, and variables in Java. In this java final tutorial we will see what is a final keyword in Java, what does it mean by making final variable, final method and final class in java and what are primary benefits of using final keywords in Java and finally some examples of final in Java. Final is often used along with static keyword in Java to make static final constant and you will see how final in Java can increase the performance of Java application.

What is Type Casting in Java? Casting one Class to other class or interface Example

Type casting in Java is to cast one type, a class or interface, into another type i.e. another class or interface. Since Java is an Object-oriented programming language and supports both Inheritance and Polymorphism, It’s easy that Super class reference variable is pointing to SubClass objects but the catch here is that there is no way for Java compiler to know that a Superclass variable is pointing to SubClass object. This means you can not call a method that is declared in the subclass. In order to do that, you first need to cast the Object back into its original type. This is called type casting in Java. You can type cast both primitive and reference type in Java. The concept of casting will be clearer when you will see an example of type casting in the next section.

How to use Lombok Library in Java? Example Tutorial

Hello Java programmers, if you have been doing professional Java development, you may have heard about Lombok library, one of the most popular Java libraries among professional Java developers, making coding in Java much more fun and rewarding. Java has always been criticized for its verbosity, and many programming languages like Scala and Groovy are invented to solve that problem, but Lombok solves that problem in Java itself. This means you don't need to learn a new programming language, but you can use the Lombok library and its annotations to write clear and concise code in Java. 

Recursion in Java with Example – Programming Tutorial for Beginners

Recursion is one of the tough programming techniques to master. Many programmers working on both Java and other programming languages like C or C++ struggles to think recursively and figure out the recursive pattern in the problem statement, which makes it is one of the favorite topics of any programming interview. If you are new to Java or just started learning Java programming language and you are looking for some exercise to learn the concept of recursion then this tutorial is for you. 

Difference between Class and Object in Java and OOP with Example

Class and Object are the two most important concepts of Object-oriented programming language (OOPS)  e.g. Java. The main difference between a Class and an Object in Java is that class is a blueprint to create different objects of the same type. This may look simple to many of you but if you are a beginner or just heard the term Object Oriented Programming language might not be that simple. I have met many students, beginners, and programmers who don’t know the difference between class and object and often used them interchangeably.

Observer design Pattern in Java with Real world code Example

Observer design pattern in Java is a fundamental core Java pattern where Observe watches for any change in state or property of Subject. For Example, Company updates all its shareholders for any decision they make here Company is Subject and Shareholders are Observers, any change in the policy of company and the Company notifies all its Shareholders or Observer. This was a simple real-world explanation of the Observer pattern. 

How to get current date, month, year and day of week in Java program - Example tutorial

Here is a quick Java tip to get the current date, month, year, and day of the week from the Java program. Java provides a rich Date and Time API though having thread-safety issue but it's rich in function and if used locally can give you all the date and time information that you need for your enterprise Java application. In the last Java tutorial on Date and Time API we have seen how to get the current date and time from different timezone using DateFormat and SimpleDateFormat classes and in this post, we will get some more details like the current month, year, day of the week, etc by using java.util.Calendar class.  Just keep in mind that the Calendar instance should not be shared between multiple threads.

Double Checked Locking on Singleton Class in Java - Example

Singleton class is quite common among Java developers, but it poses many challenges to junior developers. One of the key challenges they face is how to keep Singleton class as Singleton? i.e. how to prevent multiple instances of a Singleton due to whatever reasons. Double-checked locking of Singleton is a way to ensure only one instance of Singleton class is created through an application life cycle. As the name suggests, in double-checked locking, code checks for an existing instance of Singleton class twice with and without locking to double ensure that no more than one instance of singleton gets created.

How to convert milliseconds to Date in Java - Tutorial example

Do you want to convert milliseconds to Date in Java? Actually java.util.Date is internally specified in milliseconds from epoch. So any date is the number of milliseconds passed since January 1, 1970, 00:00:00 GMT and Date provides constructor which can be used to create Date from milliseconds. Knowing the fact that Date is internally maintained in milliseconds allows you to store date in form of milliseconds in Server or in your Class because that can be effectively expressed with a long value.

Coursera Full-Stack Web Development with React Specialization Review

Hello guys, if you are looking for the best Coursera courses to learn Fullstack development using React.js or just want to join Full Stack Web Development with React Specialization in Coursera but are not sure whether it's worth it not then you have come to the right place. Earlier, I have shared the best React courses and in this article, I will review Coursera's most popular React course. Full-stack web development is the new area of software development where one person is talked to create the whole website, and there is a huge demand for full-stack developers. It's a difficult job but salary hikes and career opportunities make it very attractive and that's why a lot of developers are learning about Fullstack development.

3 Examples to Print Array Elements/Values in Java - toString and deepToString from Arrays

Printing array values in Java or values of an array element in Java would have been much easier if  arrays are allowed to directly prints its values whenever used inside System.out.println() or format and printf method, Similar to various classes in Java do this by overriding toString() method. Despite being an object, array in Java doesn't print any meaningful representation of its content when passed to System.out.println() or any other print methods. If you are using array in method argument or any other prominent place in code and actually interested in values of an array then you don't have much choice than for loop until Java 1.4.

How to check if a number is a palindrome or not in Java - Example

How to check if a number is a palindrome or not is a variant of popular String interview question how to check if a String is a palindrome or not. A number is said to be a palindrome if the number itself is equal to the reverse of number e.g. 313 is a palindrome because the reverse of this number is also 313. On the other hand, 123 is not a palindrome because the reverse of 123 is 321 which is not equal to 123, i.e. original number. In order to check if a number is a palindrome or not we can reuse the logic of How to reverse a number in Java.

How to check if String contains another SubString in Java? contains() and indexOf() example

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1. For example "fastfood".indexOf("food") will return 4 but "fastfood".indexOf("Pizza") will return -1. This is the easiest way to test if one String contains another substring or not.

How to Find Square Root of a Number in Java? Example Solution

Write a program to calculate the square root of a number in Java or C++ is one of the popular coding interview questions from Programming job interviews both on tech companies like Facebook, Amazon, and investment banks like Citibank and Bank Of America, etc. The problem may look easy because you might know how to find the square root of a number but it's not. In fact, it's one of the tricky questions you would encounter in programming job interviews. The first hurdle is do you really remember how to calculate square root by hand? Many programmers don't. I know they have learned it past but when you ask them to calculate square root by hand, many won't remember the algorithm they have learned in school or college.

Difference between mvn install, release and deploy commands in Maven - Examples

Even though there are a couple of powerful build and deployment tools that exist for Java applications like Gradle or ANT, It seems Maven is the king of them. I have used it in several Java projects over the years and it was initially ANT, but now they all use Maven with few Scala projects using Gradle. When you work with Maven you know that there are lots of commands to remember, especially if you are working on the command line. The thee Maven build commands which often confuses Java developers are mvn install, mvn release, and mvn deploy.

How to check if a String is numeric in Java? Use isNumeric() or isNumber() Example

In day-to-day programming, you often need to check if a given string is numeric or not. It's also a good interview question but that's a separate topic of discussion. Even though you can use Regular expression to check if the given String is empty or not, as shown here, they are not full proof to handle all kinds of scenarios, which common third-party libraries like Apache commons-lang will handle e.g. hexadecimal and octal String. Hence, In the Java application, the simplest way to determine if a String is a number or not is by using the Apache Commons lang's isNumber() method, which checks whether the String is a valid number in Java or not.

How to use instanceof operator in Java with example

The instanceof operator in Java is used to check if an object belongs to a particular type or not at runtime. It's also a built-in keyword in Java programming language and is mostly used to avoid ClassCastException in Java. It is used as a safety check before casting any object into a certain type. This operator has a form of object instanceof Type and returns true if the object satisfies IS-A relationship with the Type i.e. object is an instance of class Type or object is the instance of a class which extends Type or object is an instance of a class which implements interface Type.

How to Count Occurrences of a Character in String - Java Programming Example

Write a program to count the number of occurrences of a character in String is one of the common programming interview questions not just in Java but also in other programming languages like C or C++.  As String is a very popular topic in programming interviews and there are a lot of good programming exercises on String like "count number of vowels or consonants in String", "count number of characters in String", How to reverse String in Java using recursion or without using StringBuffer, etc, it becomes extremely important to have a solid knowledge of String in Java or any other programming language. Though, this question is mostly used to test the candidate's coding ability i.e. whether he can convert logic to code or not.

How to remove duplicates elements from ArrayList in Java - Example

You can remove duplicates or repeated elements from ArrayList in Java by converting ArrayList into HashSet in Java. but before doing that just keep in mind that the set doesn't preserver insertion order which is guaranteed by List, in fact, that’s the main difference between List and Set in Java. So when you convert ArrayList to HashSet all duplicates elements will be removed but the insertion order will be lost. Let’s see this in action by writing a Java program to remove duplicates from ArrayList in Java.

How to read input from command line in Java using Scanner - Example

Java 5 introduced a nice utility called java.util.Scanner is capable of reading input from the command line in Java. Using Scanner is a nice and clean way of retrieving user input from the console or command line. The scanner can accept InputStream, Reader, or simply the path of the file from where to read input. In order to read from the command line, we can pass System.in into Scanner's constructor as a source of input. The scanner offers several benefits over the classical BufferedReader approach, here are some of the benefits of using java.util.Scanner for reading input from the command line in Java:

How to Convert String to long in Java - 4 Examples

How to convert a string to long in Java is one of those frequently asked questions by a beginner who has started learning Java programming language and is not aware of how to convert from one data type to another. Converting String to long is similar to converting String to Integer in Java, in-fact if you know how to convert String to Integer then you can convert String to Long by following the same procedure. Though you need to remember few things while dealing with long and String first of all long is the primitive type which is wrapped by the Long wrapper class and String is an Object in Java backed by character array.

How to print Floyd's Triangle in Java with Example

There are lots of programming exercises in Java, which involve printing a particular pattern in the console, one of them is printing the Floyd triangle in the console. In the Floyd triangle, there are n integers in the nth row and a total of (n(n+1))/2 integers in n rows. This is one of the most simple patterns to print but helpful in learning how to create other more complex patterns. The key to develop patterns is using nested loops and methods like System.out.print() and println() appropriately. Actually, pattern-based programming tasks are originally designed to master loops in programming.

5 Best Free Coursera Course to learn Data Science in 2021

Hello guys, if you want to learn Data Science on Coursera and looking for free Coursera Courses for Data Science then you have come to the right place. Earlier, I have shared both the best Coursera courses for Data Science as well as 15 Free Coursera courses where I have shared few free Data Science courses but many of you asked more, hence, I have created this article where I have shared 5 best free Coursera courses for Data Science. These courses have been chosen from top universities like Johns Hopkins and the University of Michigan as well as famous tech companies like IBM. You can audit these courses for FREE to learn key Data Science concepts in 2021. 

Why main method is public static in Java

The main method in Java is the first programming method a Java programmer knows when he starts learning Java programming language. have you ever thought about why the main method in Java is public, static, and void, of-course Yes, since most of us first learn C and C++ than we move to Java in our programming path we familiar with the main method but in Java main method is slightly different it doesn't return any value like in C it returns an int, the main method is public static and void Why?

Constructor Chaining in Java Example - Calling one constructor from another using this and super

Constructor Chaining in Java
In Java, you can call one constructor from another and it’s known as constructor chaining in Java. Don’t confuse between constructor overloading and constructor chaining, the former is just a way to declare more than one constructor in Java. this and the super keyword is used to call one constructor from other in Java. this() can be used to call another constructor of the same class while super() can be used to call a constructor from superclass in Java. Just keep in mind that this() in reality calls the no-argument constructor of the same class while this(2) calls another constructor of the same class which accepts one integer parameter.

How to Escape String Literal in Java Using Eclipse IDE? Example

Whenever you paste String in Eclipse which contains escape characters,  to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash, etc. This problem is more prominent when you are pasting a large chunk of data which contains escape characters like a whole HTML or XML file,  which contains lots of single quotes e.g. ‘’ and double quotes “” along with forwarding slash on closing tags. It’s very hard to manually escape all those characters and it's pretty annoying as well.

Top 3 Free and Best Svelte.js Online Courses to Learn in 2021

Hello guys, you might have heard about Svelte.js or svelte, another JavaScript framework for building component-based UI. What? A new JavaScript framework? come on give me a break. Well, It's a little bit different with established Javascript frontend frameworks like React, Vue.js, and Angular in the sense that it's more like a compiler than a framework or library. In a framework-based application, you ship your code and framework code to the client and they work together in runtime to create magic. While in the case of Svelte.js you don't ship framework code to your client, instead you ship a code generated by the Svelte compiler based upon the instruction you wrote.

9 Things about null keyword and reference in Java

Java and null are uniquely bonded. There is hardly a Java programmer, who is not troubled by the null pointer exception, it is the most infamous fact about. Even the inventor of the null concept has called it his billion-dollar mistake, then why Java kept it? Null was there from a long time and I believe the Java designer knows that null creates more problems than it solves, but still they went with it. It surprises me even more because Java's design philosophy was to simplify things, that's why they didn't bother with pointers, operator overloading, and multiple inheritance of implementation, they why null? 

How to configure Log4j in Java program without XML or Properties File - Example

Sometimes configuring Log4j using XML or properties file looks annoying, especially if your program is not able to find them because of some classpath issues, wouldn't it be nice if you can configure and use Log4j without using any configuration file e.g. XML or properties. Well, Log4j people have thought about it and they provide a BasicConfigurator class to configure log4j programmatically, though this is not as rich as their XML and properties file version is, but it's really handy for quickly incorporating Log4j in your Java program.

Does Java Pass by Value or Pass by Reference? Example

Does Java is pass by value or pass by reference is one of the tricky Java questions mostly asked on fresher level 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. 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.

How to Union and Intersection of two Set in Java - Google Guava Example

Google Guava is an open-source library that provides lots of useful utility to Java programmers,  one of them is an easy way to find the intersection and union of two Sets in Java. You might have used Google Guava for other functionality e.g. for overriding toString in an easy way or Immutable Collection provided by Guava library. Along with Apache commons and Spring, Google Guava is a library you definitely want to include in your Project. Guava provides a couple of static methods to operate on Set in Java on package com.google.common.collect.Sets.

What is Constructor in Java with Example – Constructor Chaining and Overloading

What is constructor in Java
Constructor in Java is a block of code which is executed at the time of Object creation. But other than getting called, Constructor is entirely different than methods and has some specific properties like name of the constructor must be same as name of Class. Constructor also can not have any return type, constructor’s are automatically chained by using this keyword and super. Since Constructor is used to create object, object initialization code is normally hosted in Constructor. Similar to the method you can also overload the constructor in Java

How to sort HashMap by key and value in Java - Hashtable, Map Example Tutorial

Sorting HashMap in Java is not as easy as it sounds because unfortunately, Java API doesn't provide any utility method to sort HashMap based on keys and values. Sorting HashMap is not like sorting ArrayList or sorting Arrays in Java. If you are wondering why we can not use Collections.sort() method than for your information it only accepts List<E>, which leaves us to write our own utility methods to sort Map in Java. This is true for all types of Maps like Hashtable, HashMap, and LinkedHashMap. TreeMap is already a sorted Map so we don't need to sort it again. 

How to comment uncomment single line and block of code in Java - Eclipse Tips Tricks Example

Knowing Eclipse shortcut to comment and uncomment single line or block of code can save you a lot of time while working in Eclipse. In fact I highly recommend every Java programmer to go through these top 30 Eclipse shortcut and  10 java debugging tips in Eclipse for improved productivity.  If you are Java programmer, coding in Eclipse and want to comment and uncomment single line or block of code quickly you can either use ctrl + / to comment a single line and subsequently uncomment a commented line. If you want to comment a block of code or a complete method, you have two options you can either line comment (//) all those selected lines or block comment (/* */) those lines.

Java TreeMap Tutorial: 15 Example of TreeMap in Java

TreeMap in Java is a SortedMap and it maintains Sorting order when you insert an object on it. You can specify Sorting order while Creating TreeMap by providing an explicit Comparator to TreeMap. Basically, you can create TreeMap in Java in different ways, a TreeMap with natural sorting order, and TreeMap with custom Sorting Order by providing Comparator, Copying Sorting order from other SortedMap, etc. TreeMap has a specific constructor for these conditions. We will see these in the section on creating instances of TreeMap in Java. 

How to parse String to Enum in Java | Convert Enum to String with Example

Converting Enum into String and parsing String to Enum in Java is becoming a common task with the growing use of Enum. Enum is very versatile in Java and preferred the choice to represent bounded data and since is almost used everywhere to carry literal value it's important to know how to convert Enum to String in Java. In this article, we will see both first converting Strings to Enum in Java and then Change an Enum to String in Java with Example. I thought about this Enum tutorial when I wrote 10 Examples of Enum in Java. I missed String to Enum conversion and one of the readers pointed out that. So here we have now.

Top 10 Free Courses to Learn Docker in 2021 - Best of Lot

I have been answering a lot of questions about what programmers should learn in 2021, and Docker Container is one such skill. Docker and containers are a whole new way of developing and delivering applications and IT infrastructure. In this post, I'll talk about what Docker is and why a programmer should learn Docker. In today's world of massive scalability, where every single mobile app and web application needs to support billions of users (think of Youtube, WhatsApp, Uber), software application development and deployment have become increasingly complex. Gone are the days when the software is developed by a small team of onshore people.

Top 10 Coursera Certifications, Courses, and Specializations in 2021 - Best of Lot

Hello guys, if you are looking for the best Coursera courses, certification, and specialization to join in 2021 then you have come to the right place. In the last few articles I have shared the best Coursera courses to learn PythonSoftware Development, and Cloud Computing, and today, I will share the best Coursera courses, specializations, and certifications you can join in 2021. Taking online courses and certifications have become mandatory in order to have a professional and successful career and the process is similar to the college education just by staying at your home taking classes watching videos and pass the quizzes and done you are now officially certified and when it comes to the best platform to learn online no one can compete with Coursera.

How to split String in Java by WhiteSpace or tabs? Example Tutorial

You can split a String by whitespaces or tabs in Java by using the split() method of java.lang.String class. This method accepts a regular expression and you can pass a regex matching with whitespace to split the String where words are separated by spaces. Though this is not as straightforward as it seems, especially if you are not coding in Java regularly. Input String may contain leading and trailing spaces, it may contain multiple white spaces between words and words may also be separated by tabs. Your solution needs to take care of all these conditions if you just want words and no empty String.

How to Check if two Rectangles Overlap in Java? Collision Detection Solution and Example

Can you write a Java program to check if two rectangles are overlapping with each other or not? is one of the frequently asked coding questions on tech giants like Facebook, Amazon, Microsoft, and others. This is also a kind of problem where it's easy to find opposite or negative conditions like when rectangles are not overlapping and then inverting the result to prove that rectangles are colliding with each other. I first heard about this problem from one of my friends who were in the Android game development space. He was asked to write an algorithm to find if given rectangles are intersecting or not.

3 ways to get number of months and year between two dates in Java? Examples

Earlier I have talked about how to calculate the number of days between two dates in Java (see here), and now you will learn how to get the number of months and years between dates. Though it may look easy, it's not that easy to calculate months and years between dates, unless you take care of all kinds of nuisances like Daylight saving time and when daylight change occurs, leap seconds, and an extra day added in a leap year. Unfortunately, JDK doesn't have a standard method like the Period.between() methods of Java 8 before solving this problem.

How to Serialize Object in Java - Serialization Example

Serialization is one of the important but confusing concepts in Java. Even experienced Java developers struggle to implement Serialization correctly. The Serialisation mechanism is provided by Java to save and restore the state of an object programmatically. Java provides two classes Serializable and Externalizable in java.io package to facilitate this process, both are marker interfaces i.e. an interface without any methods. Serializing an Object in Java means converting it into a wire format so that you can either persist its state in a file locally or transfer it to another client via the network, hence it becomes an extremely important concept in distributed applications running across several JVMs.

Iterative QuickSort Example in Java - without Recursion

The quicksort algorithm is one of the important sorting algorithms. Similar to merge sort, quicksort also uses divide-and-conquer hence it's easy to implement a quicksort algorithm using recursion in Java, but it's slightly more difficult to write an iterative version of quicksort. That's why Interviewers are now asking to implement QuickSort without using recursion. The interview will start with something like writing a program to sort an array using a quicksort algorithm in Java and most likely you will come up with a recursive implementation of quicksort as shown here. As a  follow-up, the Interviewer will now ask you to code the same algorithm using Iteration.

How to do static import in Eclipse - Java Example Tutorial

Do you know what is a shortcut to doing static import in Eclipse? Well, I didn't know before, but today I come to know that shortcut Ctrl+Shift+M (Source > Add Import) can not only be used to add missing imports but can also help with static import in the Java program.  Suppose you are using lots of static variables from a utility class e.g. TimeUnit by referring them with the class name, just like we refer to static variables. In Eclipse IDE, you can select the whole reference variable and press Ctrl+Shift+M and it will automatically import that static element using static import in Java.

What is Object in Java and Object Oriented Programming? Example Tutorial

Object in Java
Object in Java programming language or any other Object-oriented programming language like C++ is the core of the OOPS concept and that's why the name. Class and Object along with Inheritance, Polymorphism, Abstraction and Encapsulation form the basis of any Object-oriented programming language e.g. Java. Objects are instances of Class, Class defines blueprints and Objects are things that are created based upon that blueprint. Object is also known as instances in Java, e.g. When we say an instance of String class, we actually mean an Object of String class. The object has state and behavior in Java. 

When to make a method final in Java? Example

The final keyword in Java is not as mysterious as volatile or transient, but still, it creates a lot of doubts in programmers' minds. I often receive questions like, When to make a method final in Java or When to make a method static in Java, later I answered in my earlier post. Questions like this are not trivial, knowing what a keyword does is just a small part of mastering that functionality. Similar to the real world, where knowing that a sword can cut a lot of things is not enough for a warrior to survive, you need to know how to use that and more importantly, use it effectively. 

Where is Java used in Real World?

If you are a beginner and just started learning Java, you might be thinking about where correctly Java is used? You don't see many games written in Java except Minecraft, desktop tools like Adobe Acrobat, Microsoft Office are not written in Java, neither are your operating systems like Linux or Windows, so where exactly do people use Java? Does it have any real-world application or not? Well, you are not alone, many programmers ask this question before starting with Java, or after picking Java as one of the programming languages of choice at the graduate level.

How to read and write in 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. 

Why getter and setter are better than public fields in Java? Example

public modifier vs getter and setter method in Java
Providing getter and setter method for accessing any field of class in Java may look unnecessary and trivial in the first place, simply because you can make field public and it’s accessible from everywhere in Java program. In fact, many programmers do this in their early days but once you start thinking in terms of enterprise application or production code, you will start seeing how much trouble it can create in terms of maintenance

How to use BlockingQueue in Java? ArrayBlockingQueue and LinkedBlockingQueue Example Tutorial

Hello Java Programmers, if you have ever implemented a classical producer-consumer problem in Java then there is a great chance that you may have heard about BlockingQueue class from the Java concurrency package. It's a very useful class to implement inter-thread communication in Java without you having to write low-level wait and notify code.  BlockingQueue in Java is added in Java 1.5 along with various other concurrent Utility classes like ConcurrentHashMap, Counting Semaphore, CopyOnWriteArrrayList etc.

Top 10 JDBC Interview questions answers for Java programmer

JDBC Interview Question and Answer
JDBC Questions are an integral part of any Java interview,  I have not seen any Java Interview which is completed without asking the single JDBC Interview question, there is always at least one or two questions from JDBC API. Some of the popular questions like Why you should use PreparedStatement in Java,  Difference between PreparedStatement and CallableStatement in Java and few questions are related to improving the performance of the JDBC layer by applying some JDBC performance tips.

Top 20 Core Java Interview Questions and Answers from Investment Banks

Core Java Interview Question Answer
This is a new series of sharing core Java interview questions and answer on the Finance domain and mostly on big Investment banks. Many of these Java interview questions are asked on JP Morgan, Morgan Stanley, Barclays, or Goldman Sachs. Banks mostly asked core Java interview questions from multi-threading, collection, serialization, coding and OOPS design principles. Anybody who is preparing for any Java developer Interview on any Investment bank can be benefited from this set of core Java Interview questions and answers. I have collected these Java questions from my friends and I thought to share them with you all. 

What is Factory method Design Pattern in Java with Example - Tutorial

Factory design pattern in Java one of the core design pattern which is used heavily not only in JDK but also in various Open Source framework such as Spring, Struts and Apache along with decorator design pattern in Java. Factory Design pattern is based on Encapsulation object oriented concept. Factory method is used to create different object from factory often refereed as Item and it encapsulate the creation code. So instead of having object creation code on client side we encapsulate inside Factory method in Java. One of the best examples of factory pattern in Java is BorderFactory Class of Swing API.

Top 10 Struts Framework Interview Questions and Answers

This time it's Struts interview questions, After writing Spring interview questions a few weeks back I was thinking about what to pick for my interview series and then I thought about any web framework, and on that struts is my favorite. Struts are open-source frameworks used for web applications. These Struts interview questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for anyone who is not very familiar with struts. The best way to use these interview questions does revise before going for any Struts interview or any Java or J2EE interview.

How to Create File and Directory in Java Example - Java IO Tutorial

How to create a File and directory in Java is probably the first thing that come to mind when we are exposed to the file system from Java. Java provides rich IO API to access contents of File and Directory in Java and also provides lots of utility methods to create a file, delete a file, read from a file, and write to file or directory. Anybody who wants to develop an application in Java should have a solid understanding of IO and Networking package. 

How to Find Missing Number on Integer Array of 1 to 100 - BitSet Example

One of the most frequently asked questions on programming interviews are, write a program to find the missing number in an array in Java, C#, or any other language; depending upon which language you choose. This kind of coding interview questions are not only asked in small start-ups but also on some of the biggest technology companies like Google, Amazon, Facebook, Microsoft, mostly when they visit the campus of reputed universities to hire graduates. The simplest version of this question is to find missing elements in an area of 100 integers, which contains numbers between 1 and 100. 

How to use Array in Java? Example Tutorial

The array is one of the most important data structures in any programming language, at the same time different programming languages implement and treat array differently. Anyone who is done some programming knows the value of array and the importance of knowing about array type, using them in their program. Together with a linked list, array forms a set of basic data structures. Though Java offers excellent Collection API and some of the collection classes like ArrayList and  HashMap, they are internally based on the array.

Difference between final, finally and finalize method in Java

What is the difference between the final, finally, and finalize method is asked to my friend in a Java interview with one of the US-based Investment banks. Though it was just a telephonic round interview, he was asked a couple of good questions e.g. how to avoid deadlock in Java, How to get() method of HashMap works, and one of the puzzles which are based on recursion. In short final keyword can be used along with variable, method, and class and has a different meaning for all of them. finally is another Java keyword is used in Exception handling along with try, catch, throw, and throws. finalize() is a special method in Java that is called by Garbage Collector before reclaiming GC eligible objects.

Difference between static vs non static method in Java - Example

In this article, we will take a look at the difference between the static and non-static methods in Java, one of the frequently asked doubts from Java beginners. In fact, understanding static keyword itself is one of the main programming fundamentals, thankfully it's well defined in the Java programming language. A static method in Java belongs to the class, which means you can call that method by using class name e.g. Arrays.equals(), you don't need to create an object to access this method, which is what you need to do to access non-static method of a class.

Open Closed Design Principle in Java - Benefits and Example

Great Example of Open Closed Design Principle
I am a big fan of design pattern articles and love to read articles on design patterns and recently wrote about decorator design pattern in JavaObserver patternstatic factory pattern and Singleton pattern. Today I come across this good article on open closed design patterns, what I like most is there example and clear way of explanation, first example is true value and it will help you understand open closed principle very quickly and second example is also not bad.

How to Create and Run a batch file in Windows - .bat File Example

batch files and shell scripts are developers best friend, they help to improve productivity a lot. They not only help you to automate boring, time consuming task but also saves lot of time doing and doing them again. Batch file also reduce chances of error, once tested and encourage re-usability by sharing them across team or people with similar needs. Though not every programmer, developer or computer user has mindset to use batch file, something it's too difficult to write, some just not able to fight with initial resistance and many of them are not even aware of batch file.

4 Ways to Search Java Array to Find an Element or Object - Tutorial Example

Searching in Java Array sounds familiar? should be,  because it's one of the frequently used operations in Java programming. The array is an index-based data structure that is used to store elements but unlike Collection classes like ArrayList or HashSet which has contains() method, the array in Java doesn't have any method to check whether an element is inside an array or not. Java programming language provides several ways to search any element in the Java array

How to setup Java Environment and run Java Program from command prompt - Helloworld Example

This article contains HelloWorld Example in Java and step by step guide to run a Java program from the command prompt. Beginners who just started to learn Java or using Java often struggled and don't know how to run a Java program from the command prompt. Running a Java program is simple but setting up a Java environment is rather cumbersome especially if you are new in the Programming world and not very familiar with words like PATH, CLASSPATH, or even command prompt.

Java String Replace Example Tutorial

This String replace example in Java will show you how to replace String in Java both at the character level and by using regular expression. Since String is final in Java every time you replace String you will get a new String object only if your actually replace anything on original String otherwise replace methods of String return same String object. String Class in Java provides 4 methods to replace String in Java. Those methods allow you to replace character from String, replace CharacterSequence from String, replace all occurrence of pattern in String or just first occurrence of any pattern in Java.