Posts

Showing posts with the label Java_Language_Features

Difference between Comparator and Comparable

Java has two interfaces that you can use for sorting custom objects. These are the Comparator and Comparable interface. In this article, I will be explaining the differences between the two. Basic difference between Comparator and Comparable The main difference between the Comparator and Comparable interface is that you can use Comparator  to compare two independent objects. The Comparable on the other hand is used to compare the current object with another object. Consider the following Person class: public class Person { private String name; private int age; public Person(String name, int age) { super(); this.name = name; this.age = age; }} Suppose you want to sort Person objects on the basis of the age fields. Let us understand how you can achieve this using both Comparator and Comparable. Sorting Using Comparator In order to sort using Comparator, you will first need to create a class that implements the Comparator interface.  The following code demonstrates this...

Java Queue Interface Methods Explained With Code Samples

One of the lesser known Collection interfaces in the java.util.Queue interface. In this article, I will be covering this interface in detail. What is the Java Queue interface? The java.util.Queue interface extends the java.util.Collection interface. It provides a First In First Out (FIFO) behavior and you can use it to represent a Queue data structure.  It has several implementations in the Collection API. The java.util.LinkedList and java.util.PriorityQueue are the most common implementations Java Queue Interface Operations There are several methods available on the queue interface that help to perform various queue operations. add The add method supports adding an element to the Queue. if for some reason the add method is unable to add the element, it throws an  Exception. Sample Code (Without Exception) Queue<String> daysOfTheWeek = new LinkedList<String>();daysOfTheWeek.add("Monday");daysOfTheWeek.add("Tuesday");daysOfTheWeek.add("Wednesda...

Constructors in Inheritance - Different scenarios explained

In this article, I will be covering how constructors work in inheritance. How Constructor invocation works in Inheritance Constructor invocation works slightly differently when inheritance is involved. When an object of the sub-class is created, it implicitly invokes the c onstructor in the base class . Once the code in the base class constructor is completed, control returns to the sub class constructor and the code is the sub-class constructor is executed. There are different scenarios in which the invocation differs slightly. Let’s explore these scenarios Scenario 1 – Base class has a constructor When the base-class has a constructor, creating an object of the sub-class results in automatic invocation of the base class constructor. Consider the following code snippet: public class Animal{public Animal() {System.out.println("In Animal constructor");}}public class Cat extends Animal{public Cat() {System.out.println("In Cat constructor");}} Here, The Animal class ...

Java Method Overloading Explained with Code Samples

Java method overloading allows defining two or more methods within the same class that share the same name. Method overloading makes the code clean and increases the readability of the code. Method overloading helps to achieve polymorphism which is one of the object oriented principles.  In this article, I will be covering method overloading in detail. Introduction When methods are overloaded, their parameter declarations need to be different. The following code demonstrates this: public class AdditionService {             int add() { // no parameters             return 3+5;       }             int add(int i) { //one integer parameter             return i+i;       }             int add(int i,int j) { //two integer parameters             return i+j;       }             double add(double i,double j) { //two double parameters             return i+j;       }            } This class has 4 methods with the name add . All four add methods differ in the parameters , so there is no compilation...

Java Varargs explained with code samples

Java supports passing a variable number of arguments (varargs) to a method. In this article, I will be explaining this feature. What is varargs JDK 5 added the varargs feature, which allow creating a method that accepts a variable number of arguments. Prior to the varargs support, if you wanted to create a method with variable arguments, you either had to overload the method or use a Collection or array as a parameter. Varargs Syntax A variable number of arguments is specified using an argument name and three dots. The following code demonstrates this: void method myMethod(String ...str){//method body} This specifies a String argument str which is a vararg. So you can invoke this method as follows: myMethod("a"); //with 1 parametermyMethod("a","b"); //with 2 parametersmyMethod("a", "b", "c"); //with 3 parameters Code Sample The following code demonstrates a code sample that uses varargs: public class VarargDemo { public stat...

Java Try With Explained with Code Samples

The Java try with statement allows you to declare some resources with the try statement. Java automatically closes these resources once the try statement ends. This makes the code clean. Java introduced the try-with statement as part of Java 7. Without Try/With Consider the following code that does not use try-with: public static void saveFile(String fileName, String content) { try { BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName)); bufferedWriter.write(content); bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } This code uses BufferedWriter to write to a file. Once the code finishes writing the content to the file, it closes the BufferedWriter. Using try/With You can re-write the above code using a try-with statement as follows: public static void saveFile2(String fileName, String content) { try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileName))){ bufferedWriter.write(content); ...

Java Callable Interface Explained with Code Samples

In this article, I will be explaining the Callable interface in Java. I will be explaining what is Runnable and Callable in Java and what is the use of the Callable interface. Runnable Interface Right from the start, the Runnable interface has been associated with multi-threaded programming.  The Runnable interface provides a run method that executes code in a separate thread. The following code demonstrates this: public class RunnableDemo { public static void main(String[] args) { System.out.println("Creating new thread in main"); Runnable r = () -> System.out.println("Executing thread body...."); Thread myThread = new Thread(r); myThread.start(); System.out.println("Completed main"); }} So this code first creates a new Runnable interface and uses a lambda expression to implement the run method.  The code then creates a new Thread and invokes the start method which spawns a new Thread and executes the code in the Runnable implementatio...

Java Final Keyword Explained with Code Samples

In this article, I will be covering Java’s final keyword. I will be demonstrating the final keyword in Java with an example. Introduction You can use the final keyword with a method or instance field. When you use it with a method, it prevents the method from being overridden. When you use it with a field, it prevents the field from being modified. Final Method public class Base {public final void show() {System.out.println("In show”);}}public class Sub extends Base {// This method causes a compilation errorpublic void show() {}}}     Class Base has a method show which is marked as final Sub is a sub-class, it overrides show There is a compilation error in Sub as the final method cannot be overridden   Final Field Declaring a variable as final prevents its contents from being modified. This means that you must initialize a final variable when it is declared. The following code demonstrates a final field: public void aMethod() {final int d = 10;d = 3; // compilat...

Java Protected Keyword explained With Code Samples

In this article, I will be covering the Java Protected Keyword. Introduction Just like private and public, protected is an access specifier. When the protected access specifier is used for a field or method, it becomes accessible in all the subclasses of the class in which the field is defined. The protected access specifier also makes the member accessible in other classes which are in the same package as the class having the protected member.   Accessing a protected field from a sub-class The following code snippet demonstrates how you can access a protected field in a sub-class: package demo;public class Base {private int a;protected int b;}public class Sub extends Base {public void subMethod() {super.a=4; //this causes compilation errorsuper.b=9;}} The class Base has a private field a and a protected field b The class Sub extends Base It has a method subMethod which assigns some values to a and b a=4; – This causes a compilation error since a is private b=9 – This ...

Java Super Keyword explained

What is the Super Keyword? Super keyword is used to access members of the superclass from the subclass. It can be used to access both instance fields and methods. Code Sample Consider the following code: public class Base { int a; int b; public void baseMethod() { System.out.println("In base class method”); }}public class Sub extends Base { int c; public void subMethod() { super.a=4; super.b=9; super.baseMethod(); System.out.println("In sub class method"); } } There are 2 classes, Base and Sub Sub is a sub-class of Base ; it has a method called subMethod The base fields a,b are accessed via the super keyword in subMethod The base method baseMethod is also accessed via the super keyword When this code is executed, it will print the following output: In base class methodIn sub class method Points to Remember The super keyword is a bit redundant for instance fields and methods since as long as the instance fields and method of the sup...

Java Arrays explained with code samples

Introduction An array is essentially a list of values referred to by a common name. Java arrays can be one-dimensional or multi-dimensional. Declaring and Initializing an Array Consider the following code snippet: int myArray[];myArray = new int[10];   Here, int refers to the type of data that will be stored in the array and myArray is the name given to the array. In the second line myArray is allocated memory. The new keyword is used.  [10] – indicates the size of the array. So this statement creates a new array with space for 10 integer values. The declaration and memory allocation can also be combined into a single statement as follows: int myArray[] = new int[10];   Accessing the elements of an array Each value within the array is called an element in the array. You can access any element in an array by specifying its position within square brackets . The array index begins at 0, so the 1 st element is at position 0, the 2 nd at position 1 and so on. Consider t...

Java If else

In this blog post, I will be explaining how the if else statement works in Java. What is if-else The if-else statement is used to check for a condition. If the condition specified after the “if” keyword is true, the code following the if keyword is executed. If the code following the if keyword is false, the code following the else keyword is executed. Syntax if(condition){//some code here}else{ // this part is optional//some code here} Code Sample 1 Consider the following code snippet: int a = 20;int b = 15;if(a > b){System.out.println("a is greater than b");}else {System.out.println("a is less than b");} Variables called a and b are declared and initialized to 20 and 15 respectively The if keyword is followed by a condition i.e. a > b Since a > b is true, the code within the if block is executed If a > b was false, the code within the else block would have been executed   When this above code is executed, it will print the followi...

Nested Classes explained

Quite often, we come across the term “Nested Class” in Java. It is a very common interview topic as well. So in this blog post, I will be explaining what a nested class is in Java. What is a Nested Class? As the word suggests, a nested Java class is a class which lies within another Java class.  Consider the following code snippet: class OuterClass{class NestedClass{}}   The class NestedClass is like any other member of the OuterClass . It has access to other members that is methods and variables of the OuterClass even if a member is a private member. On compiling this code snippet, the compiler creates two class files. One will be the OuterClass.class and the other will be the OuterClass$NestedClass.class .  If you have more than one nested class, the compiler creates a separate class file for each one. However, each of them will be prefixed with the name of the enclosing class and the $ sign. Why do we need nested classes? The following are some reasons where you ...

Java Enumerations explained

Just like the primitive data types, there is another data type supported by Java which is the enumerated type. In this blog post, I will be explaining Java enumerations in detail. Enum definition An enumerated type is a type whose values consist of a fixed set of constants. Common examples are days of the week which take the values Sunday,Monday, Tuesday,Wednesday,Thursday,Friday and Saturday . Another example could be Colors which could take values like Red,Blue,Yellow, Green corresponding to the colors. In Java, you can define an enumerated type by using the enum keyword. The syntax is as follows: enum NameOfEnum {value1,value2,value3.......,valuen} You can have as many values as you wish. For example, you can define an enum for the days of the week as follows: enum Days {Sunday,Monday, Tuesday,Wednesday,Thursday,Friday,Saturday} The values Sunday,Monday, etc are called enumeration constants. For the enum Days, these are the only values that are allowed. You should use enumerated ...

Java Interfaces explained

In this blog post, I will be explaining what Java interfaces are and how they can be used. What is an interface? An interface is a java construct that is used to specify a behavior that classes must implement. It does this by specifying methods without any method bodies. The code for the methods within the interface must be provided by the classes that implement the interface. So using an interface , you can specify what a class must do, but not how it does it. For example, consider the following code snippet: public interface Animal {public void speak();} This interface keyword specifies that this is an interface. Instead of the class keyword, the interface keyword is used, otherwise its body is very similar to a class. There is a speak method within this interface. There is no code in the speak method. Methods specified in an interface have no method bodies.  Code is not allowed in a method in an interface since the basic concept of an interface is to use it to specify what should be...

What Are Java constructors?

A constructor is a special method that is invoked as soon as an object is created using the new operator. In this blog post, I will explaining constructors. Constructors are most commonly used to execute some code that needs to be run as soon as an object of a class is created like setting initial values to the instance variables. Consider the following code snippet: public class Person {private String firstName;private String lastName;public void setPersonDetails(String firstName,String lastName){this.firstName=firstName;this.lastName=lastName;}} Here, there is a Person class. There is a method called setPersonDetails . This method sets values to the firstName and lastName fields. However we need to invoke this method, each time we create a Person object. If we forget to invoke this method, the firstName and lastName fields will not be set . So we need some way for the person details to be automatically set when a Person object is created. Fortunately, Java supports this aut...

What are Iterators in Java?

Java provides an interface called Iterator that is used to iterate over or loop through the elements in a collection. You can use an iterator on any Collection interfaces or any of its sub interfaces like List or Set .   Consider the following code snippet: public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for(int i = 0; i &amp;lt; 10; i ++){ list.add(i+2); } Iterator<Integer> itr = list.iterator(); while (itr.hasNext()){ int i = itr.next(); System.out.println("i="+i); } }   This code demonstrates how you can use iterator to iterate over a List. Here, we are iterating over a list of integers. But you can use it to iterate over any data type. The iterator method on the list interface returns an iterator instance. In the iterator variable declaration, we need to specify the data type that the iterator will iterate over. In this case, we are specifying Integer.  Once we obtain an iterator, we ca...

Java classes and objects explained

In this blog post, I will be explaining the distinction between classes and objects. The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. public class Book {String bookName;String bookAuthor;} This is a very simple class called Book. This class keyword is used to declare a class.You can see here that I’ve declared some variables in the class. These variables are called instance variables or fields . This Book class acts as a template and we can create many books using this class. Now consider the following code snippet: public class Demo {public static void main(String args[]){Book book = new Book();}} The first line creates a new object of type Book and assigns it to the variable book . This object book will have its own copies of the variables bookName and bookAuthor. Each object contains its own copy of each instance variable defined by the class. A class acts like a templa...

Java prefix and postfix notation explained

You might have used the increment and decrement operators in Java.  You can use these in prefix and postfix form. In this blog post I will be explaining the difference between the two. When you use the increment or decrement operator before the operand it is said to be in prefix form. In such cases the increment or decrement operation is performed first before evaluating the expression. int i = 5;int j = ++i;System.out.println("j="+j);System.out.println("i="+i); This code prints the following output: j=6i=6 So here value of j is 6 because the increment operation is performed first. However when the increment or decrement operator is used after the operand it is said to be in postfix form. In such cases the increment or decrement operation is performed after evaluating the expression. int i = 5;int j = i++;System.out.println("j="+j);System.out.println("i="+i); This code prints the following output: j=5i=6 So here value of j is 5. This is because t...

Java loops Examples

In this blog post, I am going to demonstrate all of Java’s loops. I am going to write loops that prints the sum of numbers in a List. For Loop private static int sumFor(List<Integer> numbers){int sum = 0;for(int i=0; i < numbers.size();i++){sum += numbers.get(i);}return sum;}   For Each Loop private static int sumForEach(List<Integer> numbers){int sum = 0;for(int num:numbers){sum += num;}return sum;} While Loop private static int sumWhile(List<Integer> numbers){int sum = 0;int i = 0;while (i < numbers.size()){sum += numbers.get(i);i++;}return sum;} Do While Loop private static int sumDoWhile(List<Integer> numbers){int sum = 0;int i = 0;do{sum += numbers.get(i);i++;}while (i < numbers.size());return sum;}