What is Constructor in Java and How it works? [with Example]

In simple word, Constructor is a method like a block of code which is called by Java runtime during object creation using new() operator. Constructor are special in the sense that they have the same name as the Class they are part of. They are also special in a sense that they are called by JVM automatically when you create an object. Have you ever thought about Why do you need a constructor? What benefits it provide? One reason is to initialize your object with default or initial state since default values for primitives may not be what you are looking for. One more reason you create constructor is to inform the world about dependencies, a class needs to do its job. Anyone by looking at your constructors should be able to figure out, what he needs in order to use this class.  For example, following class OrderProcessor needs a Queue and Database to function properly.

Difference between ReentrantLock vs synchronized lock in Java? Example Tutorial

In concurrent programming, synchronization is essential to ensure that multiple threads can safely access shared resources without causing data inconsistencies or race conditions. In Java, there are two primary mechanisms for achieving synchronization: ReentrantLock and the synchronized keyword.  The ReentrantLock and synchronized lock both serve the purpose of allowing exclusive access to critical sections of code, but they differ in terms of flexibility, performance, and the level of control they provide to developers. Understanding the nuances between these two synchronization approaches is crucial for Java developers aiming to build efficient and reliable concurrent applications.

Difference between an ordered and a sorted collection in Java? Example Tutorial

Hello guys, if you are working in Java collection framework then you may have heard about ordered as well as sorted collection classes. One of the related question to this concept is what is difference between ordered and sorted collection in Java, which is often asked to junior developers. In the past, I have shared 25 Java Collection interview questions as well as 130+ Java questions and in this article, I will answer this popular question. An ordered collection maintains the order of elements e.g. ArrayList maintains the insertion order of elements. Similarly LinkedHashMap can keep element in the order they are inserted or accessed. 

3 Examples to Loop Map in Java - Foreach vs Iterator

There are multiple ways to loop through Map in Java, you can either use a foreach loop or Iterator to traverse Map in Java, but always use either Set of keys or values for iteration. Since Map by default doesn't guarantee any order, any code which assumes a particular order during iteration will fail. You only want to traverse or loop through a Map, if you want to transform each mapping one by one. Now Java 8 release provides a new way to loop through Map in Java using Stream API and forEach method. For now, we will see 3 ways to loop through each element of Map

5 Examples of Formatting Float or Double Numbers to String in Java

Formatting floating point numbers is a common task in software development and Java programming is no different. You often need to pretty print float and double values up-to 2 to 4 decimal places in console, GUI or JSP pages. Thankfully Java provides lots of convenient methods to format a floating point number up to certain decimal places. For example you can use method printf() to format a float or double number to a output stream. However, it does not return a String. In JDK 1.5, a new static method format() was added to the String class, which is similar to printf(), but returns a String. By the way there are numerous way to format numbers in Java, you can use either DecimalFormat class, or NumberFormat or even Formatter class to format floating point numbers in Java. 

How to Synchronize an ArrayList in Java with Example

ArrayList is a very useful Collection in Java, I guess most used one as well but it is not synchronized. What this mean? It means you cannot share an instance of ArrayList between multiple threads if they are not just reading from it but also writing or updating elements. So how can we synchronize ArrayList? Well, we'll come to that in a second but did you thought why ArrayList is not synchronized in the first place? Since multi-threading is a core strength of Java and almost all Java programs have more than one thread, why Java designer does not make it easy for ArrayList to be used in such an environment? 

How to add Zeros at the Beginning of a Number in Java [Left Padding Examples]

How do you left pad an integer value with zeroes in Java when converting to a string? This is a common requirement if you are working in the finance domain. There are so many legacy systems out there that expect the input of a certain length, and if your input is shorter than the specified length, you got to add zeros at the beginning of the number to make them off the right length. Java has a rich API and thankfully neither converting an integer to String is difficult nor formatting String to add leading zeros. In fact, there are multiple ways to add zeros at the start of a number or numeric string, you can either use the powerful String.format() method or its close cousin printf() method, or you can go back to DecimalFormat class if you are still working in JDK 4. Formatting, in general, is a very useful concept and as a Java developer, you must have a good understanding of that.

3 Examples to Read FileInputStream as String in Java - JDK7, Guava and Apache Commons

Java programming language provides streams to read data from a file, a socket and from other sources e.g. byte array, but developers often find themselves puzzled with several issues e.g. how to open connection to read data, how to close connection after reading or writing into file, how to handle IOException e.g. FileNotFoundException, EOFFileException etc. They are not confident enough to say that this code will work perfectly.  Well, not everyone expect you to make that comment, but having some basics covered always helps. For example In Java, we read data from file or socket using InputStream and write data using OutputStream. Inside Java program, we often use String object to store and pass file data, that's why we need a way to convert InputStream to String in Java. As a Java developer, just keep two things in mind while reading InputStream data as String :

How to reverse ArrayList in Java with Example

You can reverse ArrayList in Java by using the reverse() method of java.util.Collections class. This is one of the many utility methods provided by the Collections class e.g. sort() method for sorting ArrayList. The Collections.reverse() method also accepts a List, so you not only can reverse ArrayList but also any other implementation of List interface e.g. LinkedList or Vector or even a custom implementation. This method has a time complexity of O(n) i.e. it runs on linear time because it uses ListIterator of the given list.  It reverses the order of an element in the specified list. 

How to Read, Write XLSX File in Java - Apache POI Example

No matter how Microsoft is doing in comparison with Google, Microsoft Office is still the most used application in software world. Other alternatives like OpenOffice and LiberOffice have failed to take off to challenge MS Office. What this mean to a Java application developer? Because of huge popularity of MS office products you often need to support Microsoft office format such as word, Excel, PowerPoint and additionally Adobe PDF. If you are using JSP Servlet, display tag library automatically provides Excel, Word and PDF support. Since JDK doesn't provide direct API to read and write Microsoft Excel and Word document, you have to rely on third party library to do your job. Fortunately there are couple of open source library exists to read and write Microsoft Office XLS and XLSX file format, Apache POI is the best one. It is widely used, has strong community support and it is feature rich.

How to declare a String in Java? Example Tutorial

Hello guys, we are again with new article that is on Declaring String in Java. The main aim of this article is to give you idea about how to declare a string in java and about different ways of declaring.  Since String is a very common class in Java, as a Java developer you must know how to declare String variables and also understand the difference between String variable, String object, and String literals. In the past, I have explained difference between String object and String literal and in this article I am going to share multiple ways to declare String object in Java like creating a new String object using new() operator, concatenating String and using String literal to declare String variables in Java. 

Why is Abstract class Important in Java? [Example]

Abstract class is a special class in Java, it can not be instantiated and that's why can not be used directly. At first concept of abstraction, abstract class and interface all look useless to many developers, because you can not implement any method in an interface, you can not create an object of the abstract class, so why do you need them. Once they face biggest constant of software development, yes that is CHANGE, they understand how abstraction at the top level can help in writing flexible software. A key challenge while writing software (Java Programs, C++ programs) is not just to cater today's requirement but also to ensure that nurture requirement can be handled without any architectural or design change in your code. In short, your software must be flexible enough to support future changes.

Difference between String literal and New String object in Java

The String class or java.lang.String is a special class in Java API and has so many special behaviors which are not obvious to many programmers. In order to master Java, the first step is to master the String class, and one way to explore is checking what kind of String related questions are asked on Java interviews. Apart from usual questions like why String is final or equals vs == operator, one of the most frequently asked questions is what is the difference between String literal and String object in Java

Difference between Class and Object in Java? Answered

This article is solely for all beginner programmers, who are learning object-oriented programming languages e.g. Java, C++, or C#, and aspire to do well on any programming interview. The difference between class and object is one of the most common questions, you would like to ask a fresher coming out from college or training institute, but you would be surprised how many beginner Java programmers struggle with this question. Class and Object are two pillars of Object-Oriented Programming (OOPS) and a good understanding is a must, but when you ask this question apart from the theoretical and bookish answer that "class is a blueprint and objects are actual things created out of that blueprint", you would hardly get anything substantial.

How to Configure CORS in a Spring Boot + Spring Security application

Cross-Origin Resource Sharing (CORS) is an essential mechanism for controlling access to web resources across different domains. When developing a Spring Boot application with Spring Security, it is crucial to configure CORS properly to allow or restrict cross-origin requests based on security requirements. In this article, we will explore how to configure CORS in a Spring Boot + Spring Security application, ensuring secure and controlled access to resources. We will provide step-by-step instructions and relevant code examples to help you implement CORS effectively.

What is the actual Use of interface in Java?

An interface in Java has remained a complex topic for many beginners to understand. The first thing which puzzles many programmers is the fact that you cannot define any method inside interface, it a just declaration. By rule, all method inside interface must be abstract (Well, this rule is changing in Java 8 to allow lambda expressions, now interface can have one non-abstract method, also known as a default method). So, if you can't define anything, Why we need an interface?  what's the use of an interface, if we are anyway going to write a class and override them to provide behaviour, Can't we declare those methods inside the class itself without using interface etc. Well, if you are thinking in terms of behaviour then you are really missing the point of interface.

How to use Modulo , Modulus, or Remainder Operator in Java? [Example]

Modulo Operator is one of the fundamental operators in Java. It's a binary operator i.e. it requires two operands. In a division operation, the remainder is returned by using the modulo operator. It is denoted by the % (percentage) sign. For example, 5%2 will return 1 because if you divide 5 with 2, the remainder will be 1. For a programmer it's very important to know how to use this operator, they are very important to build logic. For example, in many cases like reversing a number or checking if a number is a palindrome, you can use the modulus operator with 10 to get the last digit, for example, 101%10 will return 1 or 1234%10 will return 4, the last digit. 

How to Print Array with elements in Java? [Solution + Example]

You cannot print array elements directly in Java, you need to use Arrays.toString() or Arrays.deepToString() to print array elements. Use toString() if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional array. Have you tried printing arrays in Java before? What did you do? just passed an array to println() method and expecting it prints its elements? Me too, but surprisingly array despite being Object and providing a length field, doesn't seem overriding the toString() method from java.lang.Object class. All it prints is type@somenumber. This is not at all useful for anyone who is interested in seeing whether an array is empty or not, if not then what elements it has etc.

How to Remove Duplicates from ArrayList in Java [Example]

ArrayList is the most popular implementation of the List interface from Java's Collection framework, but it allows duplicates. Though there is another collection called Set which is primarily designed to store unique elements, there are situations when you receive a List like ArrayList in your code and you need to ensure that it doesn't contain any duplicate before processing. Since with ArrayList you cannot guarantee uniqueness, there is no other choice but to remove repeated elements from ArrayList. 

How to Sort a List into Ascending and Descending Order in Java? Examples

ArrayList, Set Sorting in Ascending – Descending Order Java
Sorting List, Set, and ArrayList in Java in ascending and descending order is very easy, You just need to know the correct API method to do that. For example Collections.sort()  method will sort the collection passed to it,  doesn't return anything just sort the collection itself. From Java 8 onwards you can also use List.sort() method to sort a List in ascending or descending order directly without using Collections.sort() method. If you like to use Stream API, it also provide a sort() method to sort elements inside Stream. You can also use that to sort any List. For example, you can first convert a List to Stream and then sort the Stream and collect the result into another List. 

How to convert long to String in Java? Example

There are three main ways to convert a long value to a String in Java e.g. by using Long.toString(long value) method, by using String.valueOf(long), and by concatenating with an empty String. You can use any of these methods to convert a long data type into a String object. It's not very different from how you convert an int to String in Java. The same method applies here as well. String concatenation seems the easiest way of converting a long variable to a String, but others are also convenient.  

Difference between RuntimeException and checked Exception in Java

RuntimeException vs Checked Exception in Java
Java Exceptions are divided into two categories RuntimeException also known as unchecked Exception and checked Exception. Main difference between RuntimeException and checked Exception is that It is mandatory to provide try-catch or try finally block to handle checked Exception and failure to do so will result in a compile-time error, while in the case of RuntimeException this is not mandatory. The difference between checked and unchecked exception is one of the a most popular question on Java interview for 2 to years experienced developer especially related to Exception concepts.