You can use java.util.text.NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them. Most numbers that are used to represent monetary value e.g. price, amount, etc require a comma to be added to improve readability and follow conventions. For example, if your variable is storing 1 million dollars then you would like to see it as 1,000,000 rather than 1000000. Clearly, the first one is more readable than the second one. Of course, you can further format to add currency based upon locale, but this tutorial is not about that.
Learn Java and Programming through articles, code examples, and tutorials for developers of all levels.
Disclosure: This article may contain affiliate links. When you purchase, we may earn a commission.
Wednesday, June 30, 2021
What is fail safe and fail fast Iterator in Java?
Java Collections supports two types of Iterator, fail-safe and fail fast. The main distinction between a fail-fast and fail-safe Iterator is whether or not the underlying collection can be modified while it begins iterated. If you have used Collection like ArrayList then you know that when you iterate over them, no other thread should modify the collection. If the Iterator detects any structural change after iteration has begun e.g adding or removing a new element then it throws ConcurrentModificationException, this is known as fail-fast behavior and these iterators are called fail-fast iterator because they fail as soon as they detect any modification.
How to convert ByteBuffer to String in Java [Example]
You can easily convert ByteBuffer to String in Java if you know how to convert byte array to String. Why? because it's very easy to convert ByteBuffer to a byte array and vice versa. All you need to do is call the ByteBuffer.array() method, it will return you the byte array used by java.nio.ByteBuffer class, later you can easily create String from that byte array. Though always remember to provide correct character encoding while converting byte array to String.
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.
How to append text to existing File in Java? Example
In the last tutorial, you have learned how to write data to a file in Java, and in this tutorial, you will learn how to append text to a file in Java. What is the difference between simply writing to a file vs appending data to a file? In the case of writing to a file, a program can start writing from the start but in the case of appending text, you start writing from the end of the file. You can append text into an existing file in Java by opening a file using FileWriter class in append mode. You can do this by using a special constructor provided by FileWriter class, which accepts a file and a boolean, which if passed as true then open the file in append mode.
How to add element at first and last position of linked list in Java?
LinkedList class in java.util package provides the addFirst() method to add an element at the start of the linked list (also known as head) and addLast() method to add an element at the end of the linked list, also known as the tail of the linked list. Java's LinkedList class is an implementation of a doubly linked list data structure but it also implements java.util.Deque interface and these two methods came from that interface, which means they are only available from Java 1.6 onward. addFirst() method insert the specified element at the beginning of the linked list and addLast() method insert the specified element at the end of the linked list.
How to get first and last elements form ArrayList in Java
There are times when you need to get the first or last element of an ArrayList. One of the common scenarios where you need the first and last element of a list is supposed you have a sorted list and want to get the highest and lowest element? How do you get that? The first element is your lowest and the last element is your highest, provided ArrayList is sorted in ascending order. If it's opposite then the first element would be the maximum and the last element would be the minimum. This is quite easy to do in ArrayList because the first element is stored at index 0 and the last element is on index, size - 1.
Difference between Abstraction and Polymorphism in Java and OOP [Answer]
Abstraction and Polymorphism are very closely related and understanding the difference between them is not as easy as it looks. Their operating model is also very similar and based upon the relationship of parent and child classes. In fact, Polymorphism needs the great support of Abstraction to power itself, without Abstraction you cannot leverage the power of Polymorphism. Let's understand this by what Abstraction and Polymorphism provide to an object-oriented program. Abstraction is a concept to simplify the structure of your code. Abstraction allows you to view things in more general terms rather than looking at them as they are at the moment, which gives your code flexibility to deal with the changes coming in the future.
Difference between synchronized ArrayList and CopyOnWriteArrayList in Java?
What is the difference between a CopyOnWriteArrayList and a Synchronized ArrayList is one of the popular Java interview questions, particularly for beginners with 1 or 2 years of experienced programmers. Though both synchronized ArrayList and CopyOnWriteArrayList provide you thread-safety and you can use both of them when your list is shared between multiple threads, there is a subtle difference between them, Synchronized ArrayList is a synchronized collection while CopyOnWriteArrayList is a concurrent collection. What does this mean? It means is that CopyOnWriteArrayList is designed keeping concurrency in mind and it is more scalable than synchronized ArrayList if the list is primarily used for reading.
4 ways to concatenate Strings in Java [Example and Performance]
When we think about String Concatenation in Java, what comes to our mind is the + operator, one of the easiest ways to join two String or a String, and a numeric in Java. Since Java doesn't support operator overloading, it's pretty special for String to have behavior. But in truth, it is the worst way of concatenating String in Java. When you concatenate two String using + operator e.g. "" + 101, one of the popular ways to convert int to String, compiler internally translates that to StringBuilder append call, which results in the allocation of temporary objects.
How to use PriorityQueue in Java? An Example
PriorityQueue is another data structure from the Java Collection framework, added in Java SE 5. This class implements the Queue interface and provides a sorted element from the head of the queue. Though it provides sorting, it's a little different from other Sorted collections e.g. TreeSet or TreeMap, which also allows you to iterate over all elements, in the priority queue, there is no guarantee on iteration. The only guaranteed PriorityQueue gives is that the lowest or highest priority element will be at the head of the queue. So when you call remove() or poll() method, you will get this element, and next on priority will acquire the head spot. Like other collection classes which provide sorting, PriorityQueue also uses Comparable and Comparator interface for priority.
Tuesday, June 29, 2021
How to parse String to Date in Java using JodaTime Example
In this Java tutorial, we will learn how to parse String to Date using Joda-Time library, for example, we will convert date String "04-12-2014" to java.util.Date object which represents this date. Before Java 8 introduced its new Date and Time API, Joda was only reliable, safe and easy way to deal with date and time intricacies in Java. Java's own Date and Time was not that great, starting from JDK 1.1 when they made java.util.Date a mutable object and when they introduced Calendar in Java 1.2. It is one of the most criticized feature of Java on communities along with checked exception and object cloning.
Right way to Compare String Objects in Java [Example]
The String is a special class in Java, so is String comparison. When I say comparing String variables, it can be either to compare two String objects to check if they are the same, i.e. contains the same characters, or compare them alphabetically to check which comes first or second. In this article, we are going to talk about the right way of comparing String variables, but what is the wrong way? The wrong way is to compare String using the == operator. It is one area in which almost every Java programmer has made mistakes sometimes by comparing two String variables using the == operator.
How to Convert Byte array to String in Java with Example
There are multiple ways to convert a byte array to String in Java but the most straightforward way is to use the String constructor which accepts a byte array i.e. new String(byte []) , but the key thing to remember is character encoding. Since bytes are binary data but String is character data, it's very important to know the original character encoding of the text from which byte array has created. If you use a different character encoding, you will not get the original String back. For example, if you have read that byte array from a file which was encoded in "ISO-8859-1" and you have not provided any character encoding while converting byte array to String using new String() constructor then it's not guaranteed that you will get the same text back? Why? because new String() by default uses platform's default encoding (e.g. Linux machine where your JVM is running), which could be different than "ISO-8859-1".
2 Ways to Print Custom String Value of Java Enum
We all know that how powerful the enumeration type in Java is, and one of the main strengths of enum is that they can implement an interface, they can have an instance variable and you can also override any method inside enum instance. In Java programs, we often need to convert Enum to String type, sometimes just to print values in the log file and other times for storing log into the database. By default, when you print an enum constant, it prints its literal value e.g. if the name of the enum instance is RED, then it will print RED. This is also the value that is returned by the name() method of java.lang.Enum class. But, there are situations when we want a custom String value for an enum constant.
How to break from a nested loop in Java? [Example]
There are situations we need to be nested loops in Java, one loop containing another loop like to implement many O(n^2) or quadratic algorithms e.g. bubble sort, insertion sort, selection sort, and searching in a two-dimensional array. There are a couple of more situations where you need nesting looping like printing the pascal triangle and printing those star structures exercises from school days. Sometimes depending upon some condition we also like to come out of both inner and outer loops. For example, while searching a number in a two-dimensional array, once you find the number, you want to come out of both loops. The question is how can you break from the nested loop in Java.
Difference between instance and Object in Java
In Java or other object-oriented programming languages, we often use Object and instance word interchangeably, but sometimes it confuses beginners like hell. I have been often asked several times, whether object and instance are the same things or different? Why we sometimes use object and sometimes instances if they are the same thing etc? This gives me the idea to write a little bit about it. I will mostly talk about Java conventions perspective. Just like we use word function in C or C++ for a block of code, which can be called by its same, but in Java, we refer them as methods.
How to Convert a Double to Long in Java - Example Tutorial
We often need to convert a floating-point number into an integral number e.g. a double or float value 234.50d to long value 234L or 235L. There are a couple of ways to convert a double value to a long value in Java e.g. you can simply cast a double value to long or you can wrap a double value into a Double object and call it's longValue() method, or using Math.round() method to round floating-point value to the nearest integer. The right way to convert a double value to a long in Java really depends on what you want to do with the floating-point value.
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 - Apach 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 create User Defined Exception class in Java
Java has very good support for handling Errors and Exceptions, It has a well-defined Exception hierarchy and language level support to throw and catch Exceptions and deal with them. Java Programmers often deal with built-in exceptions from java.lang package and several others which are already defined in JDK API like NullPointerException. If you have read Effective Java, you may remember the advice of Joshua Bloch regarding Exception. According to him, you should try to reuse the Exception classes provided in the JDK, like IndexOutOfBoundException, ArithmeticException, IOException, and java.lang.ArrayIndexOutOfBoundsException , instead of creating new ones for a similar purpose.
How to Sort HashMap in Java based on Keys and Values
HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn't guarantee any order.
How to convert String to Float in Java and vice-versa - Tutorial
There are three ways to convert a String to float primitive in Java parseFloat(), valueOf() method of Float class, and new Float() constructor. Suppose you have a String that represents a floating-point number e.g. "3.14" which is the value of PIE, you can convert it to float by using any of those three methods. Since String is one of the most prominent data types in Java, you will often find yourself converting String to Int, Double, and other data types and vice-versa. Java designer knows about that and they have made arrangement to carry out this basic task in a predictable and consistent manner.
How to Generate Random Number between 1 to 10 - Java Example
There are many ways to generate random numbers in Java e.g. Math.random() utility function, java.util.Random class or newly introduced ThreadLocalRandom and SecureRandom, added on JDK 1.7. Each has their own pros and cons but if your requirement is simple, you can generate random numbers in Java by using Math.random() method. This method returns a pseudorandom positive double value between 0.0 and 1.0, where 0.0 is inclusive and 1.0 is exclusive. It means Math.random() always return a number greater than or equal to 0.0 and less than 1.0.
Monday, June 28, 2021
Second Highest Salary in MySQL and SQL Server - LeetCode Solution
Write a SQL query to get the second highest salary from the Employee table.
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite databases e.g. MySQL, Microsoft SQL Server, or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database.
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite databases e.g. MySQL, Microsoft SQL Server, or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database.
How to Make Executable JAR file in Eclipse IDE - Java
If you are a Java programmer then you know what is the purpose of the JAR file, but for those who are unaware, the JAR file is deliverables of Java application. Just like C and C++ applications produce EXE files, Java produces JAR files. In other words, A JAR (Java Archive) file is a ZIP format file that bundles Java classes into a single unit, it may contain all the resources needed by Java application as well. There are mainly two types of the JAR file in Java: Library JAR (normal JAR) files: JARs which are reusable libraries like Apache commons JAR file, guava.jar itself, or even JDBC drivers like ojdbc6_g.jar. There is another type as well, Executable JAR files: JARs which can be executed as standalone Java applications.
How to calculate Sum of Digits using Recursion in Java [Example]
This is the second part of our article to solve this coding interview question, how to find the sum of digits of an integer number in Java. In the first part, we have solved this problem without using recursion i.e. by using a while loop and in this part, we will solve it by using recursion. It's good to know different approaches to solving the same problem, this will help you to do well on coding interviews. While finding a recursive algorithm, always search for a base case, which requires special handling. Once you find the base case, you can easily code the method by delegating the rest of the processing to the method itself, i.e. by using recursion.
How Constructor Works in Java? [Answer]
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.
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 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.
How to Synchronize 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?
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.
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.
Why Abstract class is 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.
What is the difference between a Class and an Object in Java?
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.
Sunday, June 27, 2021
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.
Tuesday, June 22, 2021
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.
Monday, June 21, 2021
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.
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.
Subscribe to:
Posts (Atom)