Posts

Showing posts from August, 2018

What is the difference between a Set and List?

A very common question asked in Java interviews is to explain the difference between a Set and a List . So,in this post I’m going to explain this in detail. What is common between Set and List? Before I start with the differences, let me explain what is common between the two. Both Set and List are sub interfaces of the Collection interface in the java.util package. Both store a group of elements, however they differ slightly in the way they store data.   So what are the differences? Duplicates A List allows duplicate elements i.e. the same element can be present more than once. A Set on the other hand does not allow duplicates. So if the same element is added again, it will overwrite the previous value of the element. Ordering of Elements Also a List is ordered i.e. elements in a list are stored in the order in which they are inserted & this order is maintained. The List interface has a method called add. It adds object sequentially to the list, so the first object added will

How to find the number of days between two Dates

In this post, I am going to demonstrate how you can find the number of days between two dates. The following code snippet demonstrates this:   Code snippet </pre>public static void main(String[] args) {try {DateFormat df = new SimpleDateFormat("yyyy-MM-dd");Date today = df.parse("2018-08-24");Date future = df.parse("2018-09-04");// Date future = getFutureDate();int daysBetween = daysBetween(today,future);System.out.println("days between = "+daysBetween);} catch (ParseException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private static int daysBetween(Date date1, Date date2){long time1 = date1.getTime(); //Returns no of milliseconds since January 1, 1970, 00:00:00 GMTlong time2 = date2.getTime();long diffInMs = time2-time1;int numOfMsInOneDay = 1000 * 60 * 60 * 24;int daysBetween = (int) (diffInMs / numOfMsInOneDay);return daysBetween;}<pre>   Explanation The Date.getTime method is first used for each Date object.  Thi

How to find the factorial of a number

In this post, I will be showing you how to find the factorial of a number in Java. The method used in this example does not use recursion. The following code snippet demonstrates how to find the factorial of the given number:. private static int findFactorial(int num){int result = 1;for(int i =1; i <= num;i++){result = result * i;}return result;} So this method iterates from 1 till the input number. It multiplies the current value of i to the result. It continues this till the input number is reached. So if you run this code for the number 5, you will get the result as 120.      

Java Exception handling explained

In this blog post, I will explain how Java’s exception handling works.   What are the types of errors in Java? You many have encountered compilation errors several times in your code. Compilation errors  are errors that are detected when the code is compiled and even before the code is executed. However, some errors are detected and can occur only when the code is run. Such errors are broadly classified into Exceptions. Java provides a built in class called Exception to handle error conditions. There are also various sub classes of this exception class that handle some specific errors. What is an exception? Whenever an error occurs while executing a statement, Java creates an object of the Exception class. The normal flow of the program  then halts. The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. How do Java exceptions work? When the exception occurs in a method, the process of creat

How to reverse a String in Java

In this post, I will demonstrate how to reverse a String in Java. You can do this in the most obvious way i.e. iterating through the String in the reverse order and creating a new String. The following code snippet demonstrates this:   private static String reverse(String str){String reversedString = &quot;&quot;;for(int i = str.length()-1;i &gt;=0 ; i--){reversedString = reversedString + str.charAt(i);}return reversedString;}   A better way is to use Java’s StringBuilder class that has an in-built reverse method. The following code snippet demonstrates this:   StringBuilder strBuilder = new StringBuilder(str);String reversedString = strBuilder.reverse().toString();  

How to find the number of words in a Sentence

In order to find the number of words in a sentence, you can use the String.split method. The following code demonstrates this:   package demo;public class StringDemo {public static void main(String[] args) {String str = "My first Java program";String[] words = str.split(" ");System.out.println("There are "+words.length+" words");}} So the split method splits the given String on the basis of the space character. It returns a String array with all the words in the input String. You can use any other character to split the String as well. When you run this code, it will print the following on the console: There are 4 words  

Object oriented principles in Java Explained in Short

As you probably know, Java is an Object-oriented language. There are some fundamental object-oriented principles that are supported by Java. In this post, I will give you an overview of the object-oriented principles supported by Java. I will also explain how Java supports them. An understanding of these OOPs principles will give you a strong foundation while writing code. Abstraction Abstraction simply means hiding the internal details from the outside world. In Java, classes & methods are used to achieve abstraction. So a class hides its internal working from the outside world & only provides public methods for the functionality which the outside world needs to access. Encapsulation Wrapping together data & code that operates on the data together as a single unit is referred to as encapsulation. Again, a well-implemented java class can be an example of encapsulation. By well implemented, I mean that the correct access specifiers are used i.e. fields should have private ac

How to find the largest number in an array

The following code demonstrates how to find the largest number in an array:   package demo;public class LargestNumberDemo {public static void main(String[] args) {Integer[] intArr = {45,21,88,210,550,1,34};int max = 0;for(int num:intArr){if(num > max)max = num;}System.out.println("Biggest number is "+max);}}   So the for loop iterates through the array. Initially, the variable max is set to 0. Each number is compared with ‘max’ and if it is greater than max, then it is assigned to ‘max’. This process is repeated till all the elements in the array are exhausted.   This will print the following output: Biggest number is 550   You can use this code to find the largest number from any Collection type like Set or List.

How to check if a String has only alphabets

You can use Java regular expressions to check if a String has only alphabets as follows: package demo;public class StringDemo {public static void main(String[] args) {String str = "HelloWorld";String regex = "^[a-zA-Z]+$";boolean matches = str.matches(regex);System.out.println(matches);}}   The above code will print true when you run it. If you change the String str to have any other characters like numbers or special characters, it will print false.

How to replace a character in a String with another character

There is a replace method provided by the String class that can be used to replace a character in a String with another character. The following code snippet demonstrates this:   package demo;public class StringDemo {public static void main(String[] args) {String str = "Hello World";String modifiedStr = str.replace('o', 'i');System.out.println("Modified String is "+modifiedStr);}}     So the above code will replace all occurrences of the letter ‘o’ in the String “Hello World”  an ‘i’ and will print the following: Helli Wirld

How to convert an Array to a List

If you have a non primitive array type, you can use the following code to convert it to a list: public class ArrayToListConverter {public static void main(String args[]){Integer[] intArr = {2,4,6,8,10};List<Integer> intList = new ArrayList<Integer>();//Method 1 - Using for loopfor(int i:intArr){intList.add(i);}//Method 2 - Via Arrays.asListintList = Arrays.asList(intArr);//} Method 1 Here, we are manually iterating through the elements in the list and adding them to an int array. Method 2  Here, we are using the Arrays.asList method. This returns a list corresponding to the array passed in. Note that this method wont work if the array is of primitive type like this: int[] intArr = {2,4,6,8,10};

How to read a file in Java

In Java, you can use the BufferedReader class as follows in order to read a file:   package demo;import java.io.BufferedReader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;public class MyTextFileReader {public static void main(String args[]){try {BufferedReader br = new BufferedReader(new FileReader(new File("F:/test.txt")));String line = null;while ((line = br.readLine()) != null) {System.out.println(line);}} catch ( IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

Java 8 Supplier Interface example

In this blog post, I will be explaining how the Java 8 functional interface Supplier works. To know more about functional interfaces, you can refer this blog post. Edit The Supplier interface provides a method called get.  This method does not accept any arguments. It can return any data type. Supplier example with Integer return type. Consider the following code snippet: public static void main(String[] args) {Supplier<Integer> getRandom = () -> new Random().nextInt(100);System.out.println("Random number 1 = "+getRandom.get());System.out.println("Random number 2 = "+getRandom.get());} Here, we have implemented the Supplier.get method using a lambda expression.  This get method simple returns a random integer less than 100. So when this code is executed, it will print the following output: Random number 1 = 98Random number 2 = 89 Supplier example with Date as return type Consider the following code snippet: public class SupplierDemo {public static vo