Fail-fast and Fail-safe iterators in java

Iterators are used to iterate or traverse over collections in java. The iterators can be fail-fast and fail-safe.
Fail-fast iterators throw exceptions at runtime (called the ConcurrentModificationException) if the collection is being modified while iterating over it.
Fail-safe iterators are those which do not throw exception if being modified while iterating because they work over the clone of the collection rather than working on the actual collection.

Iterator which iterate on HashMap, ArrayList classes are some examples of fail-fast Iterator.
Iterator which iterate on ConcurrentHashMap, CopyOnWriteArrayList classes are examples of fail-safe Iterator.

Understand with an Example !

1. Example of Fail-fast iterator

import java.util.ArrayList;
import java.util.Iterator;

public class FailFastIteratorTest {

public static void main(String[] args) {
	ArrayList<String> list = new ArrayList<>();
	list.add("john1");
	list.add("john2");
	list.add("john3");
	list.add("john4");
	list.add("john5");

	System.out.println(list);

	Iterator<String> iterator = list.iterator();
	while (iterator.hasNext()){
		if(iterator.next().equals("john3"))
		{
			list.remove("john3");
		}
	}
	System.out.println(list);
 }
}

OUTPUT

[john1, john2, john3, john4, john5]
Exception in thread "main" java.util.ConcurrentModificationException
	at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
	at java.util.ArrayList$Itr.next(ArrayList.java:859)

Problem

The problem here is that you are trying to remove an element “john3” from the list while iterating over it therefore this will lead to ConcurrentModificationException.

How to overcome it ?

So instead of list.remove(“john3”) use iterator.remove() method in the condition

while (iterator.hasNext()){
	if(iterator.next().equals("john3"))
	{
		iterator.remove();
	}
}

OUTPUT

[john1, john2, john3, john4, john5]
[john1, john2, john4, john5]

Using iterator’s remove() method you will not get any such Exception.

Important Fact :

  1. If you wish to use iterators for traversing a collection and then you intend to remove elements from that collection while iteration, then prefer using iterators remove() method as it doesn’t throw ConcurrentModificationException.
  2. There is another way to avoid exception, use fail-safe iterator collections instead, we will look into it below.

2. Example of Fail-safe iterator

As we read earlier, the fail-safe iterators do not throw concurrent modification exception because they work or iterate on the clone of the collection and not
on the actual.

But, There are a couple of drawbacks:

  1. Fail safe iterators does not always guarantee updated data, after the iterator is made if any modification is done on the collection will not reflect in the iterator as it works on the clone.
  2. One overhead is of memory and time used in creating a clone of collection to work on.

I. Example of CopyOnWriteArrayList :

import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class FailSafeIteratorTest {

    public static void main(String[] args) {

        List<String> list = new CopyOnWriteArrayList<>();
        list.add("john1");
        list.add("john2");
        list.add("john3");
        list.add("john4");
        list.add("john5");

        System.out.println(list);

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().equals("john3")) {
                list.remove("john3");
            }
        }
        System.out.println(list);
    }
}

OUTPUT

[john1, john2, john3, john4, john5]
[john1, john2, john4, john5]

Here you will observe, on using fail safe iterator on CopyOnWriteArrayList it will not throw any exception.

II. Example of ConcurrentHashMap :

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class FailSafeIteratorTest {

    public static void main(String[] args) {

        ConcurrentHashMap<Integer,String> map = new ConcurrentHashMap<>();
        map.put(1,"one");
        map.put(2,"two");
        map.put(3,"three");
        map.put(4,"four");

        System.out.println(map);

        Iterator<Integer> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            int key = iterator.next();
            System.out.println(key + " : " + map.get(key));
            map.put(5,"five");
        }
        System.out.println(map);
    }
}

OUTPUT

{1=one, 2=two, 3=three, 4=four}
1 : one
2 : two
3 : three
4 : four
5 : five
{1=one, 2=two, 3=three, 4=four, 5=five}

Here you will observe, on using fail safe iterator on ConcurrentHashMap it will not throw any exception.

3. Difference between Fail-fast and Fail-safe iterators

Fail-fast IteratorFail-safe Iterator
This kind of iterator throws ConcurrentModificationException when iterating over a collection.This kind of iterator does not throw Exception when iterating over a collection.
It iterates on the original collection.It iterates over the copy of original collection and not on the actual collection.
There is no extra memory and time overhead like fail safe iterators as they operate on actual collection.It has an overhead of extra memory and time as it works over the copy of actual collection.
Examples are HashMap, ArrayList.Examples are ConcurrentHashMap, CopyOnWriteArrayList

4. How Iterators work internally ?

Initially in the internal implementation a variable called expectedModCount is equal to modCount which is zero.

int expectedModCount = modCount;

If there is any change done in the collection, the modCOunt will change and then an exception is thrown, by calling a method checkForComodification().

final void checkForComodification() {
     if (modCount != expectedModCount)
	throw new ConcurrentModificationException();
}

Summary

In this article we learnt about Fail-fast and Fail-safe iterators, we also learnt them with examples, it’s differences and internal working.
Hope you liked the article !


How to convert String to Date in Java

In this tutorial, we will see how to convert a String into Date in Java, for many developers this is still a challenge so we try to help in making it simple.

// String -> Date
   SimpleDateFormat.parse(String);

// Date -> String
   SimpleDateFormat.format(date);

// In Java 8, String -> Date
   LocalDate localDate = LocalDate.parse(date, formatter);

// In Java 8, Date -> String
   formatter.format(localDate) // DateTimeFormatter

Refer to the table below for Date Time letter Patterns :

LetterDescriptionExamples
yYear2020
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60

Examples

1. String = “7-Jun-2020” to Date “dd-MMM-yyyy”

package com.test.dates;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtility {

    public static void main(String[] args) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");

        String dateInString = "7-Jun-2020";

        try {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date)); // returns a String

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT

Sun Jun 07 00:00:00 IST 2020
07-Jun-2020

2. String = “07182020” to DateMMddyyyy

package com.test.dates;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtility {

    public static void main(String[] args) {

        SimpleDateFormat formatter = new SimpleDateFormat("MMddyyyy");

        String dateInString = "07182020";

        try {
            Date date = formatter.parse(dateInString);
            System.out.println(date);
            System.out.println(formatter.format(date)); // returns a String

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT

Sat Jul 18 00:00:00 IST 2020
07182020

3. In JAVA 8 using LocalDate API, Convert String “dd/MM/yyyy” to LocalDatedd/MM/yyyy

package com.test.dates;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateJava8 {

    public static void main(String[] args) {

      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy");

      String date = "18/07/2020";

      LocalDate localDate = LocalDate.parse(date, formatter);

      System.out.println(localDate);

      System.out.println(formatter.format(localDate));
    }
}

OUTPUT

2020-07-18
18/07/2020

Summary

In this tutorial, we learnt how to convert String to Date in java using SimpleDateFormat and LocalDate of Java8.
Hope you liked it !


Garbage collection in Java

In java, Garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.

In the Java programming language, dynamic allocation of objects is achieved using the new operator. An object once created uses some memory and the memory remains allocated till there are references for the use of the object.

When there are no references to an object, it is assumed to be no longer needed, and the memory, occupied by the object can be reclaimed. There is no explicit need to destroy an object as Java handles the de-allocation automatically.

The technique that accomplishes this is known as Garbage Collection. Those Programs that do not de-allocate memory can eventually crash when there is no memory left in the system to allocate. These programs are said to have memory leaks.

In C language, it is the programmer’s responsibility to de-allocate memory allocated dynamically using free() function. This is where Java memory management has an advantage.

When does java perform garbage collection?

There are many ways:

  • By nulling the reference
  • By assigning a reference to another
  • By anonymous object etc
  1. By nulling a reference:
    Department obj=new Department ();
    obj=null;
  2. By assigning a reference to another:
    Department obj1=new Department ();
    Department obj2=new Department ();
    obj1=obj2; //now the first object referred by obj1
    // is available for garbage collection
  3. By anonymous object:
    new Department ();

How to request JVM for garbage collection

Before we find out these ways, we must know what is finalize()

Finalization

finalize() method is present in Object class with following prototype. Syntax : protected void finalize() throws Throwable.

Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.

Once we made object eligible for garbage collection, it may not destroy immediately by garbage collector. Whenever JVM runs Garbage Collector program, then only object will be destroyed. But when JVM runs Garbage Collector, we can not expect.

We can also request JVM to run Garbage Collector.

There are two ways to do it :

  • Using System.gc() method : System class contain static method gc() for requesting JVM to run Garbage Collector.
  • Using Runtime.getRuntime().gc() method : Runtime class allows the application to interface with the JVM in which the application is running. Hence by using its gc() method, we can request JVM to run Garbage Collector.
// Java program to demonstrate requesting 
// JVM to run Garbage Collector
public class Test
{
    public static void main(String[] args) throws InterruptedException
    {
        Test t1 = new Test();
        Test t2 = new Test();
          
        // Nullifying the reference variable
        t1 = null;
          
        // requesting JVM for running Garbage Collector
        System.gc();
          
        // Nullifying the reference variable
        t2 = null;
          
        // requesting JVM for running Garbage Collector
        Runtime.getRuntime().gc();
      
    }
      
    @Override
    // finalize method is called on object once 
    // before garbage collecting it
    protected void finalize() throws Throwable
    {
        System.out.println("Garbage collector called");
        System.out.println("Object garbage collected : " + this);
    }
}
              

OUTPUT

Garbage collector called
Object garbage collected : Test@46d08f12
Garbage collector called
Object garbage collected : Test@481779b8
              

NoteObject class finalize() method has empty implementation, thus it is recommended to override finalize() method to dispose of system resources or to perform other cleanup.

Summary

In this article we learnt about Garbage Collection in Java. Finalization in garbage collection and how to request JVM to run Garbage Collection.
Hope you liked the article !


Java Virtual Machine

JVM is an engine that provides a run time environment to convert byte code to machine language. It stands for Java Virtual Machine.

So the Java code is first compiled into bytecode. Then this bytecode gets interpreted on different machines. JVM is available for various h/w and s/w platforms and hence can be considered platform dependent.

JVM is also responsible for allocating memory space.

Java was developed with a concept of WORA (write once run anywhere) , java code is compiled into a .class file and then that class file is loaded by the JVM and it further executes it.

JVM Architecture

JVM is divided into 3 main subsystems:

  1. Class Loader Subsystem
  2. Runtime Data Area
  3. Execution Engine

How JVM works ?

1. Class Loader

It is a Subsystem , It is mainly responsible for three activities.

  • Loading
  • Linking
  • Initialization

Loading : The Class loader reads the .class file, generate the corresponding binary data and save it in method area( where it stores the fully qualified name of the loaded class and its immediate parent, it also stores the variables, modifiers and method information).

Linking : In this process, JVM performs verification(to ensure correctness of .class file), performs preparation(allocates memory to class variables) and performs resolution(where the symbolic references are replaced by direct references).

Initialization : In this process, all the static variables are assigned values defined in the code or in the static blocks from top to bottom from parent to child.

There are three built-in classloaders in Java.

  1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads the core java APIs present in JAVA_HOME/jre/lib directory. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.
  2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loades the jar files/classes located in the extension directories $JAVA_HOME/jre/lib/ext directory.
  3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from classpath. By default, classpath is set to current directory. You can change the classpath using “-cp” or “-classpath” switch. It is also known as Application classloader.

2. Run Time Data area/ JVM Memory Area

Method Area : There is only one Method Area in a JVM and it is a shared resource. It holds class level information like (class name, immediate parent class name, methods and variables info etc).

Heap Area : There is only one Heap Area per JVM and it is a shared resource as well. Class Objects are stored here.

Stack Area : It is not a shared resource but For every thread or process JVM creates one run time stack which is stored here. This stack area stores local/temporary variables. When a thread terminates its run time stack is also destroyed by JVM.

PC Registers : It stores the instruction information of executed and to be executed instructions, it is separate for each thread.

Native Method Stack : This area holds the instructions of native code

3. Execution Engine

Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and information present in various memory area and execute instructions. It can be classified in three parts

Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is that when one method is called multiple times, every time interpretation is required.

Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It compiles the entire bytecode and changes it to native code so whenever interpreter see repeated method calls,JIT provide direct native code for that part so re-interpretation is not required,thus efficiency is improved.

Garbage Collector : It destroy un-referenced objects.For more on Garbage Collector,refer Garbage Collector.

4. Native Method Interface

It enables java code to call or be called by native applications. Native applications are programs that are specific to the hardware and OS of a system.

5. Native Method Libraries

Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution Engine.

Difference between JDK, JRE & JVM

JREJVMJDK
JRE is the environment within which the java virtual machine runs. JRE contains Java virtual Machine(JVM), class libraries, and other files excluding development tools such as compiler and debugger. Which means you can run the code in JRE but you can’t develop and compile the code in JREJVM runs the program by using class, libraries and files provided by JREJDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler, debugger etc.

Summary

In this article we learnt about the Java Virtual Machine and its Architecture, we also learnt about how JVM works and the difference between jdk,jvm & jre.
Hope you liked the article !


Strings in Java

String in java is an Object that represents a sequence of characters for e.g. “Programmer” is a string of 10 characters.

In java, string is also an immutable object which means it cannot be changed once it has been created.

Syntax to Create a String

In 2 Ways:

  1. Using String Literals:
    String str1 = “Hello”;
    String str2 = “Hello”;
  2. Using new Keyword:
    String str1 = new String(“Hello”);
    String str2 = new String(“Hello”);

Using String Literals:

As you see in the above example, Two String references are created (str1 & str2). We know that Objects are created using new keyword But here we see that only 2 references are created and assigned a value “Hello” and we read above that String is an Object so how is literal creating object ?

Here the compiler does it for us automatically. The compiler creates the String Object and assigns it to the String reference str1.

Now what happens with str2 ? Does the compiler create another Object for that ? The answer is no ! Here since the Object “Hello” already exists in memory hence it is also assigned to any other reference String variables which are having the same value.

Benefit of above strategy : JVM manages memory very efficiently by not creating the same String Objects again and referencing the same Object to other variables. This is the reason JVM is having seperate memory area for String Objects created via String literals called the String Constant Pool.

The memory area where this Object is first created is called the String Constant Pool.

Using new Literals:

Seeing the above example, In this case the JVM creates 2 seperate Objects each with the same value.

Moreover, when we do String s = new String(“programmer”);

Then, inside the memory area 2 objects are created , one in the Heap area because of the new operator and one in the String Constant Pool area so that a new reference if created and assigned the same value, can point to that Object.

Other String related Classes

1. StringBuffer Class:

While String is a fixed length, immutable character sequence, StringBuffer represents a growable and writable character sequence.

StringBuffer s = new StringBuffer(“ProgrammerToday”);

2. StringBuilder Class:

It represents a mutable sequence of characters i.e it can be modified.

StringBuilder str = new StringBuilder();
str.append(“ProgrammerToday”);

3. StringTokenizer Class:

Is used to break a string into tokens.

//seperate by whitespaces	
StringTokenizer st = new StringTokenizer("Welcome programmer to this website"," ");  
    while (st.hasMoreTokens()) {  
        System.out.println(st.nextToken());  
    }  
}  

OUTPUT

Welcome
programmer
to 
this
website

Few methods of String Class:

Java String class provides a lot of methods to perform operations on strings. Few of them are : compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

String replace methods: 2 types

There are two type of replace methods in java string.

  • public String replace(char oldChar, char newChar) :
    To replace a character with another one.
  • public String replace(CharSequence target, CharSequence replacement) :
    To replace a string with another one.

Examples:

1.)

public class ReplaceExample1{  

  public static void main(String args[]){  
  String s1="Welcome to programmer today";  
  String replaceString=s1.replace('o','e');//replaces all occurrences of 'a' to 'e'  
  System.out.println(replaceString);  

}}
              

OUTPUT

Welceme te pregrammer teday
              

2.)

public class ReplaceExample1{  

  public static void main(String args[]){  
  String s1="Welcome to programmer today";  
  String replaceString=s1.replace('to','buddy at');
  //replaces all occurrences of 'a' to 'e'  
  System.out.println(replaceString);  

}} 
              

OUTPUT

Welcome buddy at programmer today
              

Why is String Immutable in java ?

Consider a situation like below :

There is one String :

String s1 = “programmer”;

We see that there is a reference variable with “programmer” as its value.

now take another reference variable s2 :

String s2 = s1.concat(“today”);
String s3 = s1;

If String was not immutable then it would have modified the value of s1 to “programmertoday” and all the other references pointing to it would have also changed.

To avoid this, String is made immutable in java and string literal concept is introduced.

Summary

In this article we learnt about the Strings in java, ways to make a String, its some very useful methods and why String is immutable.
Hope you liked the article !


Immutable Class Concept in java

Immutable simply means unmodifiable or unchangeable. Immutable class means that once an object is created, we cannot change its content. In Java, all the wrapper classes (like String, Boolean, Byte, Short) and String class is immutable.

Why is even immutability introduced at first ?

An immutable object is one whose state cannot and will not change after it’s initial creation. Immutable objects are great, mostly because they are Thread safe (and threaded code should be avoided as much as possible). You can pass them around without fear they will be changed.

Since the internal state of an immutable object remains constant in time, we can share it safely among multiple threads.

We can also use it freely, and none of the objects referencing it will notice any difference, we can say that immutable objects are side-effects free.

How to make a class Immutable

Prerequisites to create an Immutable class:

  • Class must be declared as final (So that child classes can’t be created)
  • Data members in the class must be declared as final (So that we can’t change the value of it after object creation)
  • A parameterized constructor
  • Getter method for all the variables in it
  • No setters(To not have option to change the value of the instance variable)

Examples of Immutable class :

final class EmployeeFinalClass {

  private final String empName;

  private final int empId;

  public EmployeeFinalClass(String a, int b) {
    this.empName = a;
    this.empId = b;
  }

  public int getEmpId() {
    return empId;
  }

  public String getEmpName() {
    return empName;
  }

}

class Test {

  public static void main(String[] args) {

    EmployeeFinalClass obj = new EmployeeFinalClass("Robin Hood", 1001);

    System.out.println(obj.getEmpName());
    System.out.println(obj.getEmpId());
    
    // any modification to final class properties
    // is not permitted, throws compilation error
    // Wanna Test ? - uncomment below line to check.
    
    //obj.empName="";

  }

}
            

OUTPUT

Robin Hood
1001             
            

Concept of Defensive copy

  • If a field is a mutable object create defensive copies of it for getter methods.
  • If a mutable object passed to the constructor must be assigned to a field, create a defensive copy of it.

Example to understand Defensive copy concept:

1.)  Creating defensive copy of getter method

import java.util.Date;

public class ImmutablFieldObjectTest {

  private final Date date;

  public ImmutablFieldObjectTest() {
    this.date = new Date();
  }

  public Date getDate() {
    // return date;
    return new Date(date.getTime());
  }

  public static void main(String[] args) {

    ImmutablFieldObjectTest obj = new ImmutablFieldObjectTest();
    System.out.println(obj.getDate());
    obj.getDate().setTime(obj.getDate().getTime() + 1000);

    // Now ImmutablFieldObjectTest date is not changed 
    // because we changed the copy,
    // not the original date
    System.out.println(obj.getDate());
  }

}              
            

OUTPUT

Mon Jul 29 21:13:41 IST 2019
Mon Jul 29 21:13:41 IST 2019
            

2.)  Creating defensive copy of Object – if this object is to be assigned to another object.

import java.util.Date;

public class ImmutablFieldObjectTest {

  private final Date date;

  public ImmutablFieldObjectTest(Date date) {
    this.date = new Date(date.getTime());
  }

  public Date getDate() {
    // return date;
    return new Date(date.getTime());
  }

  public static void main(String[] args) {

    Date date = new Date();
    ImmutablFieldObjectTest obj = new ImmutablFieldObjectTest(date);
    System.out.println(obj.getDate());
    date.setTime(date.getTime() + 1000);

    // Now ImmutablFieldObjectTest date is not changed. 
    // We create a copy on the constructor
    // so a change to the external date will not affect 
    // the internal state of
    // ImmutablFieldObjectTest instance

    System.out.println(obj.getDate());
  }

}            
            

OUTPUT

Mon Jul 29 22:27:43 IST 2019
Mon Jul 29 22:27:43 IST 2019              
            

Immutable Objects given by java:

  • File / String / Wrapper classes
  • JDBC apis(Callable, statement, connections) : immutable object
  • UseCases : Hashtable , adding string key

Summary

In this article we learnt about Immutable Class Concept in java and its importance. We also saw an example of Immutable class, learnt about concept of defensive copy of getter method and Object.
Hope you liked the article !


Final Keyword in Java

The Final keyword in Java allows us to set limitations on accessibility to a code i.e it adds a restriction to access.

The static keyword can be used in the following context :

  1. Final Variable : to create constants
  2. Final Method : to prevent method overriding
  3. Final Class : to prevent inheritance

1. Java final variable

When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. A final variable can be assigned value later, but only once

When to use a final variable :
final variables must be used only for the values that we want to remain constant throughout the execution of program.

Example:

              
public class FinalVariableClass {

    // a final variable direct initialization
    final int NUMBEROFITEMS = 5;

    // a blank final variable
    final int CART_CAPACITY;

    // an another blank final variable
    final int  MINIMUM;

    // a final static variable with direct initialization
    static final String COMPANY_NAME = "ProgrammerToday";

    // a  blank final static  variable
    static final double TEST_CONSTANT;

    // instance initializer block for initializing CART_CAPACITY
    {
        CART_CAPACITY = 10;
    }

    // static initializer block for initializing TEST_CONSTANT
    static{
        TEST_CONSTANT = 1.1;
    }

    // constructor for initializing MINIMUM
    // Note that if there are more than one
    // constructor, you must initialize MINIMUM
    // in them also
    public FinalVariableClass()
    {
        MINIMUM = 1;
    }

public static void main(String args[])
{
// re-assigning final variable will throw compile-time error
COMPANY_NAME = "ProgrammerToday_new";
}

}

2. Java final method

A Final method cannot be overridden

In a scenario where you feel that you method should not be overridden. So that it does not change your piece of code.

Example:

class A {
    final void display(){
        System.out.println("display method of parent class");
    }
 }
 
class B extends A{
 
    //'display()' cannot override 'display()' in 'A'; overridden method is final
    void display(){
        System.out.println("display method of child class");
    }
 
 } 
  

3. Java final class

A final class cannot be extended(inherited).

There are 2 uses of making a class final:

Example:

1. Is to prevent inheritance as the final class cannot be extended. e.g : wrapper classes like Integer, Float etc.

  final class FinalClass {
  }
  
  // The following class is not correct.
  class B extends FinalClass
  {
     // COMPILE-ERROR! Cannot inherit from final 'FinalClass'
  }
  

2. Is to make the class immutable for example like String.

FAQ , Questions and Answers

Q1. Can we initialize blank final variable ? If yes, then How ?

Sol. There are two ways to initialize blank final variable:

  1. Using constructor
  2. Using initialization block

Refer to the example above.

Q2. Can we declare a constructor as final ?

Sol. No, because it is never inherited.

Summary

In this article we learnt about Java Final Keyword and its various use cases. We saw it can be used as a variable, method and a class.
Hope you liked the article !


Static in Java

The Static keyword in Java is used mainly for memory management. The static keyword belongs to the class than an instance of the class, which means if you make a member as static then you can access it without creating a class object.

The static keyword can be used as :

  1. A variable
  2. A method
  3. A class
  4. A Block of statements

1. Java Static variable

It is common to all instances(or objects) of the class because it is a class level variable. It also means that the static variable is created only once and is shared among all the other instances of the class. A static variable can be accessed directly by the class name and doesn’t need any object.

<class-name>.<variable-name>

When and why we use static variable?

Scenario –

  1. Things like Database connection url , which may not change for a particular database
  2. An employee class, it has many employees with unique employee ids but belongs to the same company, hence company name can be put into a static variable.

Example:

public class StaticVariableTestClass {

  static int a1;
  static String a2;
  
  // This is a Static Method, calling static variables
  static void display() {
      System.out.println("Variable one is: " + a1);
      System.out.println("Variable two is: " + a2);
  }

  public static void main(String args[]) {
      display();
  }

}
  

OUTPUT

Variable one is: 0
Variable two is: null

Another Usecase : counter ++ using static variable, used as a counter variable.

2. Java Static method

  1. Static method in Java is a method which belongs to the class and not to the object. A static method can access only static data(not the instance variables)
  2. A static method can call only other static methods from it and cannot call a non-static method.
  3. A static method cannot refer to “this” or “super” keywords.
  4. A static method can be accessed directly by the class name , object instance is not needed.
<class-name>.<method-name>
public class TestStaticVariable {

  static int sum;

  // This is a Static Method
  static int sumOfTwoNumbers(int a1, int a2) {
    sum=a1+a2;
    return sum;
  }

  public static void main(String args[]) {
    sum=sumOfTwoNumbers(5,5);
    System.out.println("The sum of two numbers is : "+sum);
  }

}  

OUTPUT

The sum of two numbers is : 10

3. Java Static block

  1. Static block is a block where you can write statements to declare static variables.
  2. Static block is the first thing which JVM initializes on class load.
public class StaticBlock {

  static int number;

  static int square;

  // This is a Static Block
  // No matter where it is placed(top or bottom of code) it gets called 
  // before any other method
  static {
    System.out.println("** inside static block to initialize static variable **");
    number = 5;
  }

  // This is a Static Method
  static int squareOfANumber(int a1) {
    square = a1 * a1;
    return square;
  }

  public static void main(String args[]) {
    square = squareOfANumber(number);
    System.out.println("The square of a " + number + " is : " + square);
  }

}
    

OUTPUT

** inside static block to initialize static variable **
The square of a 5 is : 25

4. Java Static class

  1. A class can be made static only if it is a nested class which also means We can not declare top-level class with a static modifier.
  2. Nested static class doesn’t need reference of Outer class.
  3. A static class cannot access non-static members of the Outer class.
  4. A non static nested class is called the inner class.
             
public class OuterClass {

 private static String str = "ProgrammerToday";

   // nested class - as it is (inner + static)
   static class NestedStaticClass {

   // static method inside nested class
   static void displayName() {
     System.out.println("Book Name is : " + str);
   }

   // non-static method inside nested class
   void displayContent() {
     System.out.println("This book is about technology");
   }
   }

 public static void main(String[] args) {

 // way to call static method of nested class
 OuterClass.NestedStaticClass.displayName();

 // way to call non-static method of nested class by creating instance
 OuterClass.NestedStaticClass obj = new NestedStaticClass();
 obj.displayContent();

 }

}

OUTPUT

Book Name is : ProgrammerToday
This book is about technology

Summary

In this article we learnt about Java Static Keyword and its various use cases. We sar it can be used as a variable, method, block and a class.
Hope you liked the article !


Object Oriented Programming Java

Object Oriented Programming is a programming concept that works on the principle that objects are the most important part of your program.

The primary purpose of Object-oriented programming is to increase the flexibility and maintainability of programs.

Object-oriented programming (OOP) is nothing but that which allows the writing of programs with the help of certain classes and real-time objects.

The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.

1. Object

An Object is a bundle of data and its behaviour(often known as methods). Also it is an instance of a class.

An Object also means a real world entity such as a notebook/pen/pencil etc.

Example : A cat is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

2. Class

A class is a group of similar Objects. It is a considered a blueprint using which you can create as many Objects as you like. An example could be having a class of Vehicles, and there can be Objects like 4 wheelers, 2 wheelers, etc and they will further have some properties like engine, make, model, year of manufacture, etc.

3. Constructor

A constructor is a block of statement which has same name as that of class and is used to initialize the class member properties.

Example :

public class OopsExample {

  int age;
  String name;
  
  //This is a Default constructor
  OopsExample(){
  this.name="John";
  this.age=35;
  }
  
  //And this one is Parameterized constructor
  OopsExample(String n,int a){
  this.name=n;
  this.age=a;
  }

  public static void main(String args[]){
       OopsExample obj1 = new OopsExample();
       OopsExample obj2 = new OopsExample("Jason", 40);
       System.out.println(obj1.name+" "+obj1.age);
       System.out.println(obj2.name+" "+obj2.age);
   }

}

OUTPUT

John 35
Jason 40

OOPs features : 4 of them with Examples

1. Encapsulation :
Wrapping up of data into a single unit is called Encapsulation. In terms of Java, if your are creating a Class with data members(variables) and behaviors(methods) then it means you are following encapsulation.

2. Abstraction :
Abstraction is a process when only the relevant data or information is shown to the user and other not necessary information is hidden from it.For Example, A car, In a car a driver/passenger knows only the relevant information which is required to drive the car, but how the engine is burning fuel inside, what and how it happens when you press the accelerator , what happens when you change the gear, a user doesn’t know.
He just have superficial knowledge or the use of certain equipment inside the car but not the inner functionality as a whole.

3. Polymorphism :
Polymorphism means having more than one form, In Object oriented programming language, Polymorphism refers to the ability of a variable, object or function to take on multiple forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

I. Static Polymorphism or compile time polymorphism : Achieved by method overloading, which means methods having the same name, same return type but different signature(number of parameters).

class MethodOverloading
{
    public void display(char ch)
    {
          System.out.println(ch);
    }
    public void display(char ch, int num)  
    {
          System.out.println(ch +“ - "+num);
    }
}
public class Test
{
    public static void main(String args[])
    {
        MethodOverloading obj = new MethodOverloading();
        obj.display('john');
        obj.display('john',40);
    }
} 

OUTPUT

john
john - 40

II. Dynamic Polymorphism or run time polymorphism : In dynamic polymorphism a call to overridden method is resolved at run time and that is why referred as run-time polymorphism.

class Animal{
  public void breed(){
  System.out.println("Default breed");
  }
}
public class Dog extends Animal{

  public void breed(){
  System.out.println("German Shepherd");
  }
  public static void main(String args[]){
  Animal obj = new Dog();
  obj.breed();
  }
} 

OUTPUT

German Shepherd

4. Inheritance :It is one of the code saving techniques, which helps in reducing the redundant code. It works by letting child class adapt properties of parent class, where the original class is called the parent class whereas the new one adapting the parents features is called the child class.
we use the keyword “extends” in classes and “implements” in interfaces.

Summary

In this article we learnt about Object Oriented Programming in Java and its 4 major concepts. We also learnt about Object, Class and its Constructor.
Hope you liked the article !


Difference between Abstract Class and Interface in Java

The Difference between Abstract Class and Interface is as follows:

TopicAbstract ClassInterface
Method TypeAbstract class can have abstract and non-abstract methods.Interface could have only abstract methods upto java 7, but later from java 8 it can also have default and static methods.
Variables TypeAbstract class can have final, non-final, static and non-static variables.Interface has only static and final variables.
Final VariablesAn abstract class may contain non-final variables.Variables declared in a Java interface are by default final.
Inheritance/Abstractionabstract class can be extended using keyword “extends”.A Java interface can be implemented using keyword “implements”.
Multiple implementationan abstract class can extend another Java class and implement multiple Java interfaces.An interface can extend another Java interface only.
Accessibility of Data membersAn abstract class can have class members like private, protected, etc.Members of a Java interface are public by default.
Limit of ExtensionsIt can extend only one class or one abstract class at a time.It can extend any number of interfaces.
Constructor or destructorsAn abstract class can declare constructors and destructors.An interface cannot declare constructors or destructors.
Examplepublic abstract class Shape{ public abstract void draw(); }
public interface Drawable{ void draw(); }

Most Important Question : When to use what?

Use Abstract Class when :

  • There is some part of functionality which seems to be common for other related classes, then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
  • Abstract class allows code reusability.

Use Interface when :

  • You need total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
  • Allows you to separate the definition of a method from the inheritance hierarchy.

Summary

In this article we learnt about the difference between Abstract Class and Interface in java.
Hope you liked the article !